All posts by admin

Mosh React tutorial (part 4) – Single Source of Truths

to run: npm install, npm start
download source

Single Sources of Truth

In Counters, create a checkState to view what your state object looks like:

Let’s initialize your state like so:

Now run your app and click on the check state button. The counters array you see in your log matches.
Now, click on your counters to increase their number.

I increased mine to 6, 6, 8, 8, 8.

Now if you click the check state button again, you’ll see that the state object in Counters is still in its initial values, and not the updated ones you just gave.

The reason why this happens is because when you increment, you are incrementing the state’s count property in Counter. The correct way is to update the counters array in Counters. We shall use Controlled Component to fix this issue.

Controlled Component

Controlled component does not have local state.

ref – http://chineseruleof8.com/code/index.php/2020/06/27/controlled-component/

  • It receives all props by data
  • Raise events whenever data needs to be changed
  • Component is entirely controlled by its parent
  • Cannot have state
counters.jsx

This is where you give data to your child component using prop attributes.
In our case, we give:
– data counter object
– counter.id as key

The two reference functions onDelete and onIncrement is to take care of the events that our child component Counter raises.

First, we handle increment in counters component. We do a deep copy. First we clone the counters array.
We then get the array index of the counter by using indexOf
Then we re-point the reference of that array element to a new literal object with same properties/values.
Then we increment the value.
We then reset our state’s counters property to our cloned counters array.

This way, we don’t use any of the old counters array.

counters.jsx

counter.jsx

Since data is received as prop from our parent Counters, we should not have any state.
All data displayed and used here should be from the prop object.
All button click events are raised to our parent component by callings its prop function references onIncrement and onDelete.

As you can see, everything we do in counter.jsx, as a controlled component, is to use this.props. Through this.props, we use callbacks to tell parent component counters to increment, or decrement. We use other values from this.props to display.

Now when we run the program, we increment our numbers in the components, then look at the state, it reflects what we’ve updated. This is because we tell our parent component to change the one and only data source to change.

Mosh React tutorial (part 3)

final source
to run: npm install, npm start

Composing Components

React App is a tree of components

Add new component in components folder.
Create counters.jsx

In index.js, instead of , we put

index.js

Go to counters.jsx and put the code template there by doing:

imrc + tab
cc + tab

Throw in some Counter components like so:

Then on the screen, you’ll see your multiple counters appear.

However, it’s all hardcoded. Let’s do it via an array instead. We create an array counters with id and value objects. Then we map through this array and pass each object into a component Counter.

That way, each Counter component will have its own id and unique value.

The only thing we didn’t do here is pass the value.
Passing values as parameter takes two steps. One is to create a prop called value, and we pass in the counter.value that way. While we’re at it, let’s create another prop ‘selected’.

The second step is to go to Counters and receive that prop.
counter.jsx

A props is just a plan JS object that includes all attributes in the Component. In your Counters component, put a console log props in the render function. Make sure you put different values in your array in your Counters components

Now when you run the app, look at the console:

You’ll notice that the whatever value we give to the props will be reflected in that Counter component’s JS object props

Now, create lifecycle componentWillMount and assign the props into the state:

counter.jsx

We do this because we want to assign the state property count to have the value from props.
Now you should see the values reflected in our counters.

Children property

Now let’s check out the children’s property in prop object.

In Counters, edit the Counters JSX so that it has a ending tag. Then, insert some JSX within our Counter component

counters.jsx

Then, if we were to look at Counter component’s prop object, we see a children property. Children is a React Element.

counter.jsx


children:
$$typeof: Symbol(react.element)
key: null
props: {children: “Testing 1 2 3”}
ref: null
type: “h4”

Because its a React Element we can put it within our JSX and thus be able to output it into our webpage like so:

counter.jsx

You’ll see the h4 JSX you entered into Counter’s component appear.

Of course, we can keep going and put dynamic data there to make it more useful by adding each counter’s id. That way each Counter component will receive the id as children property and display it.

counters.jsx

Now, we display the counter ID as they appear.

Prop vs State

Prop is data we give to Component. Prop is read-only. We cannot re-assign.
State is data that is local/private to the Component.

Raising and handling Events

In Counter, we put in a delete button. When clicked, we want to delete the data object from counters.
So we throw in handleDelete function for when clicked.

counter.jsx

However, in handleDelete, we want to remove the object from the array in Counters, which is in a another Component altogether! How should we go about doing this?

The component that owns a piece of the state, should be the one modifying it.

In Counter’s onDelete function, we raise an event. And Counters will handle this event.

On the Counters side, we must implement handleDelete() to handle this event.

Counters

In Counters, we first create handleDelete function. We then pass in a reference to this function into a Counter via property onDelete.

Counter.jsx

Whenever the delete button is pushed in Counter, it calls on the reference to Counters’s onDelete via the prop object. Of course, we pass in the id of the Counter we want to delete. Then in Counters, it removes the Counter with that id from its state array.

As you can see, we pass in the id into the Counter component’s prop. So in Counter component, this.props.id is the id of the counter. When we trigger the callback onDelete, we pass this id back to counters, which then filters out the counter object from its state’s array ‘counters’. Thus, successfully removing the counter.

Improvements

If you look at the render function of Counters, we’ll notice we have many props. It gets repetitive

What we can instead is simply pass in a counter object instead. Make sure you keep the key prop. If you don’t, React has no way to keep tract of the items and even though your data is correct, what you see on UI will not be.

Make sure you update your prop access in counter.jsx. Search and find any this.prop, and add a counter behind it.

counter.jsx

Swap table items using javascript DOM style transform

JS

ref – https://codepen.io/anon/pen/VXMdwE

HTML

CSS

toggle button

First, create the button, with its onclick handler toggleCoronaData.

Then implement toggleCoronaData.

If its closed, we animate the shifting of the div height, or whatever attribute you want to move.

If its open, we animate the opposite way.

Mixins in JS

ref – https://blog.bitsrc.io/understanding-mixins-in-javascript-de5d3e02b466

Mixin is a way properties are added to objects without using inheritance — Darren Jones
Mixins are a form of object composition, where component features get mixed into a composite object so that properties of each mixin become properties of the composite object. — Eric Elliot

Let’s create a destination object to contain all the data.

Then we create a whole bunch of other objects with properties.

Finally, we’ll write our custom assign to “mixin” these objects with properties into our destination object like so:

The result of mydetails would be:


{surname: “qi ji”, firstname: “ricky”, occupation: “Software Developer”}
surname: “qi ji”
firstname: “ricky”
occupation: “Software Developer”
__proto__: Object

It mixed in all the properties of the other objects.

Object as hash, and looping through its keys and values (JS)

Scope vs Context in Javascript

ref –

  • https://medium.com/better-programming/scope-vs-context-in-javascript-b31818f58558#28ec
  • https://stackoverflow.com/questions/14328519/different-in-scope-and-context-in-this-javascript-code

scope has two levels: global scope and local scope.

Global scope refers to variables that are accessible anywhere because they are declared outside of any individual functions or methods — usually at the top of the file. They exist in the global space, ready to be called upon at any time.

Local scope refers to variables that are accessible within the boundaries of their function. In this example, we have our initial declaration of the variable dog at the top of our file, which is assigned to the string of “goodBoy.” Immediately below, we console.log the dog variable.

As expected, this first console.log prints ‘good boy,’. Then, we have a function of showScopeExample(), which reassigns our dog variable to the string of “bad boy”.

Our re-declaration of dog inside of showScopeExample() is locally scoped. The easiest way to know this is to look at its location. The re-declaration lies in between opening and closing curly brackets, which act as barriers to the relevancy of these variables.

Limiting the accessibility of the variables declared inside of functions allows us to reuse variable names that may apply to separate parts of our code. Locally scoped variables also prevent our code from having tens or hundreds of global variables floating around the global space unnecessarily. It’s also good practice to exercise proper abstraction in our JavaScript by limiting access to variables to areas where they are needed.

In other words, Scope defines the way JavaScript resolves a variable at run time. There is only two scopes in JavaScript — global and function scope. Moreover, it also deals with something called “scope chain” that makes closures possible.

Context

Context refers primarily to the use of the keyword ‘this’. The value of ‘this‘ depends on where it is being invoked.

First Rule – Invoking this in the global space will return the entire window object. This is because the window object is the starting point of all the code we write.

But what happens if we invoke this somewhere other than the global context?

Second Rule – If we invoke this in the context of a new object, it will return that object, just as it returned the entire window object.

newContextObject.invokeThisInNewContext();

It returns the entire newContextObj. When it is invoked in the context of an object, ‘this‘ will refer to that object.

Third Rule – In JavaScript, we use classes (or function constructors) to create multiple instances of objects that share properties, even though those properties may differ in value.
By using new, it will return us an instance, where the ‘this’ is pointing to the instance itself. The ‘this’ is can be referenced within the the class/function constructors and its methods.

Furthermore, a context of a function is the value of this for that function — i.e. the object the function is called as a method of.

You can invoke this function in different contexts like this:

Different ways of Creating Objects in Javascript

ref –

  • https://coderwall.com/p/p5cf5w/different-ways-of-creating-an-object-in-javascript
  • http://chineseruleof8.com/code/index.php/2019/10/04/pure-prototype-inheritance-with-object-create/
  • http://chineseruleof8.com/code/index.php/2018/04/13/object-create/

Object() constructor

Object.create()

a references an object, with its __proto__ pointing to undefined.

ref – http://chineseruleof8.com/code/index.php/2018/04/13/object-create/

Shorthand

b references an object, with its __proto__ pointing to default Object Prototype. Which has property constructor referencing to default Object function constructor. And of course, the default Object constructor has prototype reference back to the Object Prototype.

Using new to create instance

Given function

Explain this:

JS goes into 3 steps.
First, it identifies the function:

Second, it creates the instance:

Third, it initializes the instance:

which goes something like this:

All three steps is combined to create an instance object.

As a Singleton

or using IIFE

ref – http://chineseruleof8.com/code/index.php/2017/10/12/immediately-invoked-function-expression/