We promised it about two weeks ago, we would be back on React and its wonderful usage in Divi development workflow, so we start today with our first Divi React appointment. We will focus here on React States and their usage, then in the Friday post we will see them in action in a Divi module development example.
So, let’s get started.
REACT STATES: THE BASICS
While Props are independent from the Component and come from the outside of it, States are decided right in the Component itself, this is the first major difference with Props: furthermore States let you to change their value according to user actions, network responses and anything else while you must never modify your props!
REACT STATES: WHY WE USE THEM
According to what has been said above you should already have argued why States are so important for App and Divi module development.
In fact, if without Props React itself would lose its sense, we often need to modify data and check if data change over time inside our Component and we can do it only thanks to States.
REACT STATES: A LOOK AT THE SYNTAX
Let’s dive now into the syntax of React States. If you want to declare a state you have to declare it in a ‘constructor()’ method just before your ‘render()’ one:
NOTE: When you write your constructor you always have to use the formula above ‘super(props)’ inside the constructor and pass ‘props’ as argument.
As you can see the declaration of initial states is in form of an object and you can add as many states as you want in it. You can of course modify the initial state value in additional functions using ‘this.setState()’. It technically merges the component state object declared in the constructor with the object you write inside the ‘this.setState()’ function:
NOTE: When you use the keyword ‘this’ in a custom function (different than the render() one) you always have to bind this function in your constructor() using the formula ‘this.yourFunction = this.yourFunction.bind(this)’.
Finally if we want to render our state we simply have to use the syntax we use for Props: ‘this.state.name’.
REACT STATES: A REAL EXAMPLE
We come now to a real React State example. Let’s suppose we have a component that renders a simple div with some content inside and that the background color of our div is green, we add also a button:
We want to add an event listener on our button and by clicking on it we want to change our div color. In order to do that first of alla we will add a constructor function in our component in which we set our state ‘color’ of green.
Then we add another custom function called ‘changingColor’ for example in which we change the state ‘color’ to a blue value and finally we add on ‘onClick’ event listener to our button that will call the ‘changingColor’ function.
IN THE NEXT FRIDAY POST
We are at the end of today’s post. In the Friday post we will see a real example of React States usage in a Divi module development context.
So, stay tuned! See you next post.