React State - How to create, access and change react State


React State 


react state


State is similar to props but unlike props, state can be changed. State is an object used to store property value of a component. When state is changed, it associated component is re-rendered. We can create state only in class component. 

There are two ways to create state object:-

  • Inside the class constructor
  • Directly inside the class as class property

Steps to Create State in Class component

Create a file Student.jsx in src folder

Import react and component


import React from 'react';
import { Component } from 'react';

Create class component named "Student"

class Student extends Component{

}

Create state inside the class constructor

Constructor is the first method called when class component is created that’s why state is created inside constructor.

Make sure to call parent constructor by super(props).
As class has been created in memory, so use keyword "this" to create state property.

As state is javascript object, so initialize its values just like javascript object. You can initialize state with props or directly with a value.


import React from 'react';
import { Component } from 'react';

class Student extends Component{
//constructor is reserved keyword
//props is object passed as parameter 
//from index.jxp
    constructor(props){
    //callinng parent class constructor
        super(props);
    //creating state
        this.state = {
            sName: props.name,
            sRollNo: 9898,
            sCity: 'New York'
        };
    }
}

OR

Create state directly in class as property

State can be created without writing constructor. There is no difference between both ways of creating state. To create state as property, you don’t need to use this keyword.


import React from 'react';
import { Component } from 'react';

class Student extends Component{
    state = {
            sName: props.name,
            sRollNo: 9898,
            sCity: 'New York'
    };
}


Access state object in render method

You can access state object using "this" keyword anywhere in the class component. Below, we access state in render method.


import React from 'react';
import { Component } from 'react';

class Student extends Component{
//constructor is reserved keyword
//props is object passed as parameter 
//from index.jxp
    constructor(props){
    //callinng parent class constructor
        super(props);
    //creating state
        this.state = {
            sName: props.name,
            sRollNo: 9898,
            sCity: 'New York'
        };
    }
    render(){
        return(
            <div>
                <h1>Name : {this.state.sName}</h1>
                <h2>Roll No: {this.state.sRollNo}</h2>
                <h2>City: {this.state.sCity}</h2>
            </div>
        );
    }
}
export default Student;


Event Handling

  • React event handling is similar to handling event on DOM element with few differences
  • React event name follows camelCase (as onClick) naming convention rather than lowercase (as onclick).
  • With jsx, pass function as event handler rather than string


In case of function component, write below line in render method to create a button with onClick event


<button onClick={clickHandler} >
Change State</button>

In case of class component, you need to use this keyword with event handler


<button onClick={this.clickHandler} >C
State</button>

Change State Object

State object can be changed by this.setState() method. When state changes, its component re-render and change output.

Write event handler invoked on button click and change state in event handler as


clickHandler = () => {
    this.setState({
        sName: 'trump'
    })
};

Complete code of Student.jsx file is below

import React from 'react';
import { Component } from 'react';

class Student extends Component{
//constructor is reserved keyword
//props is object passed as parameter 
//from index.jxp
    constructor(props){
    //callinng parent class constructor
        super(props);
    //creating state
        this.state = {
            sName: props.name,
            sRollNo: 9898,
            sCity: 'New York'
        };
    }
    //event handler
    clickHandler = () => {
    //changing state
        this.setState({
            sName: 'trump'
        })
    };

    render(){
        return(
            <div>
//use "this" keyword to access state
                <h1>Name : {this.state.sName}</h1>
                <h2>Roll No: {this.state.sRollNo}</h2>
                <h2>City: {this.state.sCity}</h2>
//button onClick event
                <button onClick={this.clickHandler} >
                Change State</button>
            </div>
        );
    }
}
//exporting component
export default Student;

Now Import react, react-dom and Student component in index.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import Student from './Student';

Render Student in root div container. Two attributes "name" and "rollNo" are being passed. These attributes becomes object and available in Student.jsx as props.

var root = document.getElementById('root');
ReactDOM.render(<Student 
    name='john' 
    rollNo='54534' />,root);


No comments:

Post a Comment