×

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

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 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.

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.

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 Map

React Map The map() is the standard function of JavaScript, which can be called at any array. The map() method is used for traversing and displaying a list of the similar objects of...

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.

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.

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 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 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 Redux

How to Use Redux with React Hooks It is an open-source library of JavaScript which is used for managing the application state. React uses the Redux to build the user interface....

5 minutes read.

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...

3 minutes read.

React Higher-Order Components

React Higher-Order Components In short form, Higher-Order Components are represented as HOC. The Higher-order component is an advanced technique to use component logic. HOC is a function that takes the component and returns the new...

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.

React Code Splitting

React Code Splitting React Code Splitting is the procedure of splitting the bundle files by which the files get easily loaded on the webpage. The react application bundles the files by using...

4 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 JSX

React JSX As we know, all of the React components include a render function. The Render function specifies the HTML output of a React component. JSX is an acronym of JavaScript extension that...

3 minutes read.

React CSS

What is React CSS React CSS is used to provide the style to the React applications. The style attribute adds dynamically-computed styles at render time, and it is one of the most used...

5 minutes read.

Features of ReactJS

ReactJS Features As of now, within the developers, ReactJS is gaining much popularity as the best JavaScript framework. It is crucial for the front-end ecosystem. There are some of the crucial features of ReactJS that are...

2 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.