React State example

In the post, we had known how to bind data and update UI by re-rendering template. This tutorial shows way to update data automatically without calling render template function by using React State.

Relate Posts:
React Simple Data Binding example
React Component Props example
React Note Application – React props and state example

I. How to use React State

We declare state inside constructor method of the class:

When an event occurs, for example, onClick event, a function changeState() will be called to change the state:

– We use bind() function to make this work in the callback.
– Inside changeState() event method, we call setState() function which prevState parameter is the current state and will be used for getting value of state variable.
– state {this.state.counter} is updated automatically on UI.

II. Practice

1. Goal

We will build a React Application that can receive click event to add/minus value to a variable, then update variable in UI immediately:

react-state-example-result

For setting up environment and project files, please visit: React Simple Data Binding example.
To run this example, we just need to override app.js file.

2. app.js

3. Run & Check result

– Point cmd to project folder, then run cmd: yarn install.
node_modules folder and yarn.lock file now appear in our project folder:

react-example-after-yarn-install

– Run cmd: babel src/app.js --out-file=public/scripts/app.js --presets=env,react --watch
Now, a new app.js file appear in public/scripts folder, code insides this file was generated automatically (and also update automatically whenever we modify and save src/app.js).

– Open new cmd, point to Project folder, run cmd: live-server public.
Result in Browser:

react-state-example-result

III. Source code

ReactState

By grokonez | March 28, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*