Stateful and Stateless State example in React

The tutorial provides the insight on the usage of State in ReactJS, Stateful state and Stateless state , state syntax and state examples using React.

What is State in React ?

The State is used to contain data or related information about the component in React and determines the component behavior and depicts how the data is rendered to the DOM Structure. The usage of State makes the component more dynamic and interactive.

State methods in React

The State in the component can be set by invoking the setState( ) method. To retrieve the initial state in the component, use getInitialState( ). The State can be accessed or modified within the component or sometime by the component itself.

Stateful State example in React

We need to create the constructor to be assigned with the initial state value. The defined state in the component can be accessed using this.state inside the render( ) method. The below code checks for the status value and toggle the display message. Currently the value for status is set to true . The value of state is being set using the super() in the constructor.

import React, { Component } from 'react';
class App extends React.Component {
 constructor() {
      this.state = { status: true};
      render() {
          const displayMessage = this.state.status ? (
                  <p><h3>The Application status is now - Completed.</h3></p>
              ) :  (
                      <p><h3>The Application status is currently - Inprogress.</h3></p>
                  ) ;
              return (
                      <h1> Welcome to Demo Application </h1>
                      { displayMessage }
export default App;

The Ouptut message should be:

” The Application Status is currently – completed”

Now if we change the value of status to false and rerun the application, the other message will be shown ” The Application Status is currently – Inprogress”

Response message for stateful state