How to Maintain State of Component Using Class in React.js

There are generally two types of components you can use to create React.js applications. First is Class Component, which can be created by using ES6 classes and Second is Function Component type.

If you want to store state of component then you have to use class component.

Note: Now with the introduction of Hooks it is lot easier to maintain state of React Function Components than Class Components.

Note: Earlier when there was no Hooks, it was possible to maintain state of Function Components without Class BUT it was much complex than Class Components.

In this article we’ll see how to maintain React Class Component state.

Here is the code. Just go through it. We’ll explain what is going on inside it.

‎
import React from 'react';

class App1 extends React.Component {
  constructor(props) {
    super(props);
    this.state = { cart: [] };
  }

  saveInput = (e) => {
    this.setState({ input: e.target.value });
  };

  addNewItem = () => {
    let { cart, input } = this.state;
    cart.push(input);
    this.setState({ cart: cart });
  };

  render() {
    return (
      <div>
        <input
          type="text"
          onChange={this.saveInput}
        />
        <button onClick={this.addNewItem}> Add Item </button>
        <ol>
          {this.state.cart.map((subItems, sIndex) => {
            return <li key={sIndex}> {subItems}</li>
          })}
        </ol>
      </div>
    );
  }
}
export default App1;
‎

In the above example we are adding item in the cart on the button click which user provided as input. To make cart (list of items) we should maintain state of all previously added items too.

We can make use of state property of the current object to achieve this. you can store any type of object inside this property.

In the below code we are initializing cart array to the state property.

‎
constructor(props) {
    super(props);
    this.state = { cart: [] };
}
‎

In the below code we are saving value entered in the textbox to the input state property.

‎  
saveInput = (e) => {
    this.setState({ input: e.target.value });
};
‎

Note: In the constructor you should avoid using setState(), instead you should use this.state.

After that, we are retrieving value from the states (cart & input) from this.state property. Next, we are pushing new item inside cart and again updating cart object inside state object using setState().

 ‎
addNewItem = () => {
    let { cart, input } = this.state;
    cart.push(input);
    this.setState({ cart: cart });
};
‎

Note: Whatever objects you have stored inside state property will be available for you with its name inside this.state. you can use Destructuring assignment or array to hold all objects returned from this.state property.

Finally, in the render function we are calling saveInput and addNewItem respectivaly on onChange and OnClick events. After that we are retrieving cart items from cart array (which is in state property).

To display them we are using map function of JavaScript with JSX unordered list.

We are using create-react-app for this. So you can call App1 component in index.js. Eventually, it will render inside index.html root div.

Below is index.js code

‎
import React from 'react';
import ReactDOM from 'react-dom';
import App1 from './Templist';

ReactDOM.render(
  <React.StrictMode>
    <App1/>
  </React.StrictMode>,
  document.getElementById('root')
);
‎

Here is the index.html code

‎
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
‎

That’s it.