Create and Render State in React Component

In this article, we will see how to create and access/render state in a React Component.

Creating State in React Component

We can create state in a React component by using the state property in the Component’s constructor.

Syntax for adding state


this.state = {
// add the state variables
}

For example, we can add a variable “name” in the Component’s state as :


this.state = {
name : "Ajay"
}

 

Rendering State in React Component

Once the component’s initial state is created, we can display it on the UI.

We can access the data in state using :

this.state

For example, we can access the name variable is state as :
{this.state.name}

 

Example Creating & Rendering state in React

Here is a complete example for creating and rendering state :

class HelloComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state ={
     name:"Ajay"
    }
  }
  render() {
    return (
      <div>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
};

The name variable value from state will be rendered within H1 tag in the UI.

 

© 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags