ReactJS Initial State Tutorial is today’s leading topic. Each component has its state, and we can define its initial state. Let us say, for example, if an event occurs on the web page or we receive the data from the AJAX request then we must reset the component state and update the data of the component. We can also define the Initial State for the particular component.
Example #1 ReactJS Initial State Tutorial
Step 1: Make one react project by typing the following commands.
npm install -g create-react-app
create-react-app my-app
cd my-app
npm start
It will open a browser, and at port 3000, our app is running. When you change any line of code, then you do not need to refresh the page, it will stimulate automatically, and you can see the updated view.
Step 2: Go to the src >> App.js file and define one initial state.
// App.js
import React, { Component } from 'react';
class App extends Component {
state = {
name: 'Kansiris'
};
render() {
return (
<div className="App">
{this.state.name}
</div>
);
}
}
export default App;
Here, I have defined the Initial State of the component class. If we want to change the state after clicking the button and get the AJAX request response, then we just write following line to change the state.
// App.js
this.setState({
name: 'React Tutorial'
})
Example #2
We can also define the initial state of the component by the following constructor method.
// App.js
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
name: 'Kansiris'
};
}
render() {
return (
<div className="App">
{this.state.name}
</div>
);
}
}
export default App;
Remember, you do not need to change the state directly except for the initial state, we always need to use the setState method to change the state.
Also, please do not write setState() in the constructor. It will not work.
So, our ReactJS Initial State Tutorial is over. Checkout for next React.js tutorial.
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.