×

React State

React State

The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over time. The change in the state over time happens as a response to user action or system events. The component with the state is called as Stateful components. It is a crucial part of the React component that determines the component's behavior and how it will render. They are also responsible for making a component interactive and dynamic.

A state is to keep as simple as possible. The state can be set by using the setState() method, and on calling setState(), method triggers the UI updates. A state represents the local state or information. It can be modified or accessed directly by the component or inside the component. For setting an initial state before the occurring of any interaction, we have to use the getInitialState() method.

For example, suppose that we have five components that require data or information from the state, then we have to create a container component that will keep the state for all of them.

Defining the State

For defining a state, we have to first declare a default state of values for defining the component’s initial state. To do this, add a class constructor that assigns an initial state using this.state. The ‘this.state’ property can be rendered inside render() method.

Example:

The example given below will show you how to create a Stateful component using ES6 syntax:

import React, { Component } from 'react'; 

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

  render() {
    const bio = this.state.displayBio ? (
      <p>This is tutorialandexample.com website which provides you lot of tutorials.</p>
    ) : null;

    return (
      <div>
        <h2>Hello World !!!!!</h2>
        { bio }
      </div>
    );
  }
}

export default App;

Output:

React state

For setting the state, it requires to call the super() method in the constructor. This is because this.state is uninitialized before the calling of the super() method.

Changing the State

The state of the component can be changed by using the setState() method and passing a new state object as the argument. Now, create a new method toggleDisplayBio() in the above example and bind this keyword to the toggleDisplayBio() method; otherwise, it cannot be accessible inside the toggleDisplayBio() method.

this.toggleDisplayBio=this.toggleDisplayBio.bind(this)

Example:

In the below example, we are adding a button to the render() method. On clicking the button triggers the toggleDisplayBio() method that display the desired output.

import React, { Component } from 'react';

class App extends React.Component {
  constructor() {
    super();
    this.state = { displayBio: false };
    console.log('Component this', this);
    this.toggleDisplayBio = this.toggleDisplayBio.bind(this);
  }

  toggleDisplayBio() {
    this.setState({ displayBio: !this.state.displayBio });
  }

  render() {
    return (
      <div>
        <h2>Hello World</h2>
        {this.state.displayBio ? (
          <div>
            <p>
              This is tutorialandexample.com website that has a lot of tutorials.
              This website provides you a better source of learning.
            </p>
            <button onClick={this.toggleDisplayBio}>Show Less</button>
          </div>
        ) : (
          <button onClick={this.toggleDisplayBio}>Read More</button>
        )}
      </div>
    );
  }
}

export default App;

Output:

On clicking the button triggers the toggleDisplayBio() method

On clicking the Read More button, you will see the below output, and on clicking the show less button, you will get the output of above image.

Read More button, you will see the below output

Related Topics

ReactJS Versions

ReactJS Versions The Complete set of release history of ReactJS is elaborated as follows. The complete set of full documentation of recent releases is on GitHub. S.noVersionRelease DateExplanation1.0.3.029/05/2013Initially released for public.2.0.4.029/07/2013Supporting comments...

4 minutes read.

React Component Life-Cycle

React Component Life-Cycle In ReactJS, the creation process of every component includes several lifecycle methods. These methods, together stated as component's lifecycle. Four phases of the component's life cycle are as...

4 minutes read.

React Flux

React Flux Introduction It is an application architecture that is internally used by Facebook to build the client-web application with react. It is useful when the project includes dynamic data, and...

2 minutes read.

React Events

React Events An event is an action that triggers a response of the user action or system-generated event. As HTML, React can also perform actions based on user events. React has the...

2 minutes read.

React Props

React Props A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute...

3 minutes read.

ReactJS Tutorial

ReactJS Introduction React Tutorial helps you to understand the basic and some advanced concepts of ReactJS. As of now, it is the essential front-end library that is developed by a...

3 minutes read.

Difference Between React Flux and MVC

React Flux vs MVC MVC MVC is an acronym of 'Model View Controller.' It is the architectural pattern that is used to develop the user interface. It has three different logical components: The...

2 minutes read.

React Constructors

What is constructor? The constructor is a method that is used for initializing the state of the object in the class. It calls automatically during the creation of an object in...

4 minutes read.

React Native vs ReactJS

Difference between React Native and ReactJS React Native React Native is also an open-source JavaScript framework that is used for the development of a mobile application for iOS Android and Windows. It...

6 minutes read.

React Keys

React Keys A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful...

3 minutes read.

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

3 minutes read.

Difference between Controlled and Uncontrolled component in ReactJs

Controlled Component In the controlled component, the input of the form element is handled by the component rather than the DOM. Controlled components have the functions that govern the data, which...

2 minutes read.

React Hooks

React Hooks The Hooks were introduced in React 16.8. By using React Hooks, you can use the state and other features of the React without writing a class. Hooks do not work within the classes....

5 minutes read.

React Bootstrap

React Bootstrap React has a widely used JavaScript framework for creating web applications, and Bootstrap has become the most popular CSS framework. Single-page apps have become popular from the last few...

9 minutes read.

React Animation

React Animation The animation is a procedure in which an image is manipulated to appear as a moving image. It is widely used to create an interactive web application. In React, we have to...

4 minutes read.

React Components

React Components Former, the developers used to write more than thousands of lines of code to develop a single-page application. These applications follow the structure of traditional DOM, and it was very challenging to make...

2 minutes read.

ReactJS vs AngularJS

Difference between ReactJS and AngularJS AngularJS AngularJS is the JavaScript framework that is open source, and it is also used to build a dynamic web application. It is developed in 2009 by...

5 minutes read.

Difference Between State and Props in React

Comparison between State and Props State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over...

2 minutes read.

React Refs

React Refs The word ‘Refs’ is an abbreviation of ‘References’ in React. It is as similar as Keys in React. Refs are a function in React which is used for accessing the DOM element and...

7 minutes read.

React Component API

React Component API It is a top-level API. It provides reusability to the code in the application and makes it completely individual. It has several methods for: Creating Elements.Transforming Elements.Fragments. Now, we are explaining the three...

2 minutes read.