What is state and props in react.

Today, we will discuss state and props in react. In my previous posts, I already shared installation process of react and the introduction to a component in react.  I hope these posts will help you to do a quick start with react. So now I am going to give an introduction about state and props in react.

What is the state?

A state is variable that serve the value of overall render function of the component. You can also use this outside of the render function and it provides the bindings between UI and logic functions.

Initialize the state:

You can initialize the state into the constructor of component:

import React, { Component } from 'react';
class MyComponent extends Component {
       constructor(props){
             super(props);
          this.state={
           stateName:''
        }
     }
         render() {
             return (
       <div>
           <p>{this.state.stateName}</p>
      </div>
    );
  }
}
export default MyComponent;

Use of state:

You can use the state into the HTML element, react component and display state value etc.…

<p>{this.state.stateName}</p>

Update the state:

For update the state value use setState() method.

updateState(){
this.setState({stateName: ‘some value’});
}

What is props?

With the help of props, you can transfer value from one component to another component. You can pass some value into the component where you use like attribute value and you will get this props value in the entire component body with variable this.props.propsName.

Assign the props value:

<MyComponent propsName=’some value’ />

Here you can pass props value into the MyComponent. You can pass any type value like string, object, array etc.

Get and use of props value

You can get props value in that component where you assign the value of props.

import React, { Component } from 'react';
class MyComponent extends Component {

render() {
   return (
       <div>
         <p>{this.props.propsName}</p>
      </div>
     );
   }
}

export default MyComponent;

Here you will get props value with the help of this.props.propsName. now it will print the value of props that is “some value”.
One more thing you can also set the value of props with the help of state for example:

<MyComponent propsName={this.state.stateName} />

Means you can also update the value of props every time with the help of the state.

In this article, I am trying to explain the use of state and props so if you already installed the react app and created the component after this article will help you to move on the react js

I hope this article was very helpful for you, for getting in touch with new technologies our articles will always help you.

How to install and start with React

Introduction to react component | Create component with react

Leave a Reply

Your email address will not be published. Required fields are marked *