React – State

By | 12/06/2020

In this post, we will see how to use State in a Class Component.
But, what is State?
State is a special object of the Class Component, which allows components to create and manage their own data.
It is where we store property values that belongs to the component and, when it changes, the component re-renders.
It is important to reminder that, we can define a State only into the Class Component’s constructor.

We start to define a class component called dog:

[DOG.JS]

import React, {Component} from 'react'

class Dog extends Component{  
    constructor() {
        super();
        this.state = {
          number: "first",
          name: "Dorian",
          sex: "He"
        };
      }
    render()
    {
        return (
            <div>
                <h1>My {this.state.number} dog</h1>
                <p>
                    {this.state.sex} is a Chihuahua and the name is {this.state.name}
                </p>
            </div>
            ); 
    }
}

export default Dog



Then, we add this component into App.js:

[APP.JS]

import React from 'react';
import './App.css';
import Dog from './components/dog'


function App() {
  return (
    <div className="App">
      <header className="App-header">
        <Dog></Dog>
      </header>
    </div>
  );
}

export default App;



If we run the application, this will be the result:

Now, we will add the ChangeDog method into the class component dog, in order to change the value of the State:

import React, {Component} from 'react'

class Dog extends Component{  
    constructor() {
        super();
        this.state = {
          count: 0,
          number: "first",
          name: "Dorian",
          sex: "He"
        };
      }
    
      ChangeDog(){
          if(this.state.sex==="She")
          {
            this.setState(
                {
                    count: this.state.count + 1,
                    number: "first",
                    name: "Dorian",
                    sex: "He"
                });
          }
          else
          {
            this.setState(
                {
                    count: this.state.count + 1,
                    number: "second",
                    name: "Rosalia",
                    sex: "She"
                });
          }
      }

    render()
    {
        return (
            <div>
                <h1>My {this.state.number} dog</h1>
                <p>
                    {this.state.sex} is a Chihuahua and the name is {this.state.name}
                </p>
                <button onClick={() => this.ChangeDog()}>Change Dog</button>
                <p>Number of clicks: {this.state.count}</p>
            </div>
            ); 
    }
}

export default Dog



Now, if we run the application, this will be the result:

… and so on…



Leave a Reply

Your email address will not be published.