React JS States with Examples

React JS States: In this tutorial, we are going to learn about the states in React JS with examples.
Submitted by Godwill Tetah, on November 10, 2020

React JS state is where the values of a component's properties are stored.

With React JS states we can change the value of a React JS component in a different line of code.

React JS state is used to store and update React JS props values without actually using a database.

With React JS states, operations like a store, update, and delete.
All React JS components have a built-in state object.

Syntax:

class App extends React.Component {
  constructor (props) {
    super (props) ;
    this.state = { ... };
  }

The state object is then initialized at this.state and then accessed similarly like in vanilla JavaScript objects as seen in the example below.

Example:

Create the App component file called App.js and type the following,

In the App.js file, create a new class component called App with the constructor function placed before the render function.

Use this.state to create an object of properties which we will access them below.

Please be careful when creating your object of props because people forget putting the comma after each item.

Finally, export your App component.

import React from "react"

class App extends React.Component {
  constructor (props) {
    super (props) ;
    this.state = {
      name : "Carrine Asonyu",
      level: "university"
    };
  }
render () {
  return(
    <div>
    <h1> 
    Hi, i am called {this.state.name} and i am at the {this.state.level} level </h1>
    </div>

    );
  }
}

export default App

Output:

React JS States with Examples

The this.setState() Method

The value of props in a state object can be changed from a different line of code using the method; this.setState().

This can be applied during different events occurring within your React JS app or an event may trigger the change of a component's props. We will look deeper into that when handling events.

Example:

Create an App.js file and create your App component.

import React from "react"

class App extends React.Component {
  constructor (props) {
    super (props) ;
    this.state = {
      name : "Carrine Asonyu",
      level: "university"
    };
  }
  Update = () => {
    this.setState({name: "John"});
  }
render () {
  return(
    <div>
    <h1> 
    Hi, i am called {this.state.name} and i am at the {this.state.name}
     level.  </h1>
      <button type="button"
          onClick={this.Update}
        >Update</button>
    </div>

    );
  }
}

export default App

From the code above, you can see that the this.setState () method is associated with an on-click even which when clicked, the name property updates.

Output:

React JS States with Examples (1)

After On-click event

React JS States with Examples (2)



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.