Today, we will go through the one of the basic example of react. In this post we will see how to build a react component and how they interact and communicate with each other.
In this example we are going to create two buttons and based on the click of the button, we are going to change the state of the label i.e. changing the text of the label.
So to begin with this we example, first we have to create ‘react Components’ for button and label. For button we can create a reusable component which takes the name and click function as the parameter. So we can reuse this button by passing the name and click function as per our requirement and the button will invoked the exact function which we have passes to it. This implementation will explain how the properties (props) can be passed from parent to child.
As you can look into the code, we are accessing the function and name using ‘this.pros.onclick’ & ‘this.props.name’. The props represents the attribute which we have supplied to Button component. And if you observe carefully we have passed different function to each button. In similar way the ‘Label’ has been implemented.
Now we will come to the part about the changing the label text on click. In react the important thing to keep in mind is that every change in UI is get handled through the state change. So in short to change the text on the click, we have to change the state of the application. Basically state is the collection of properties which defines the current state of the application.
The function ‘getInitializeState‘ is the function provided by react to intialize the state once and later on we can change the states. This is what we have done exactly the same with label. We have initialize label with some default value and we are changing the state of the label on click of the button. Behind the scenes when we change the state the ‘Render’ function will get called automatically and the receptive DOM will get re render. This is the example of stateful component. Just keep in mind that this state change approach will force ‘render’ method only in case of ‘stateful’ component. This will not be the case if we used stateless component. In that case we have wrap the stateless component in side stateful component or ‘redux form’ or any other options. We will discuss about the this stateless component in later posts.
That’s all my friends… 🙂