You should understand that React JS props are read only. Therefore, changing the value will display an error.
This is therefore where React JS States come in to store the values of the props but allowing possibility to change the state using a method.
Let us see how we can create React JS state, use it and update the state. When creating a state, have in mind that React JS state is an object.
class Hello extends React.Component {
constructor (props) {super (props);this.state = {first_name : 'trycoder',last_name : 'blog'}}render() {return // code here}}
Adding State in the class component requires passing props in the constructor () method and super () function.
Access the information passed in the state is done by simple calling the state object dot the property. For example;
this.state.first_name
The code above will display the value of the first name.
Note that, a function component can not use state or have its own state except through hooks which will be covered in subsequent tutorials.
Let us create and use our state using a class component in our create-react-app boiler-plate code and see the output. We will create a Hello component in a new file called Test.js
Modify the file index.js to be as follows and create a new file called Test.js and add code as seen below.
index.js
import React from 'react';
import ReactDOM from 'react-dom';import Hello from './Test'ReactDOM.render(, document.getElementById('root'));
Test.js
To change the value of a property in the state object, we will use the setState( ) method. When ever the value of state is changed, the component re-renders.
The code below updates the first name using setState() after a button click.
Test.js
OUTPUT
Comments
Post a Comment
Please do not enter any spam link in the comment box.