Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

A complete guide on React fundamentals: Props and State


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

A complete guide on React fundamentals Props and State

Table of Content

Introduction

When we talk about State and Props, both are considered as variables, but they work for different tasks and purposes. To manage the structure of reacting data props can only pass it by using unidirectional from parent component to child.

What are props?

Props are defined in the parent component as variable and pass the value to the child component. Normally we familiar with C and C++ we define the variable before we must declare the variable. Same as it props are declared on one component (parent) and define in another component(child). Props follow the uni-directional flow (from parent component to child component). We can say that props are read-only components because it just assigns a value and passes the value as parameter.

How to declare props?

Here Details are child component which is imported in a parent component


Title its props attribute and my first props are props value


We can also pass the array as props using list

     const value= [1, 2, 3, 4, 5];


How to pass the value?

Props are normally used for the set the internal which is based on props value which we define in constructor like that.


 class Details extends React.Component {
  constructor(props) {
    super(props)
    console.log(props.title)
  }
}


We can directly assign in the render method


 render {
 return (<div><h2>Suject details:</h2>
<h2>{this.props.title}</h2></div>
      )
}

Props never change the value it only passes the value. Props also used to allow the child component to access the method In the parent component. There is a good way to manage the state in the parent component. Every time component will display some kind of information which is based on the props.

 
Parent Component

import &amp;#39;./App.css&amp;#39;;
import React from &amp;#39;react&amp;#39;;
import Details from &amp;#39;./Details&amp;#39;;


class Footer extends React.Component
 {

    render()
    {             
    var person =
     {
      sub1: &amp;#39;Java&amp;#39;,
      sub2: &amp;#39;php&amp;#39;,
      sub3:&amp;#39;React&amp;#39;
     };

     const value= [1, 2, 3, 4, 5];

    
     return (<div classname="">
          {/* Details component which accepts props */}<details title="my first props"></details></div>
      );
  
        
  }
    
}
export default Footer;


Child Component
import React, { } from 'react';
  
class Details extends React.Component 
{
  render() 
  {
Const {sub1,sub2,sub3}={...this.props};/// expmple of sperad and rest 
const {a}={...this.props.item}

   return(      

Suject details:

{this.props.item}

{this.props.title}

  1. sub1:{sub1}
  2. sub2:{sub2}
  3. sub3:{sub3}
) }

What is State?

The state is mange the data it can change the data while props never change the data state even set the state of data when we perform any event like button click or input change event we have to set the state of data that time state performs their task for managing the overall data.

How To Update a Component’s State?

State can not be modified directly we have to modify with a special method called setstate()

        this.setState=name:’rahi’     //wrong        
        this.setState({name: ‘rahi’})    //right


What happens when the state changes?

The state will be changed depending on the input when the time input changes then the event will be triggered and that time state is rendered and the state collects the initial value of the state. When the state change reacts then it takes the all information immediately and re-render the DOM only which component gets an update in the state, and that’s why it react faster.

Can we use state in every component?

There are two components, one is the functional component and the second is the class component. The function is also called the stateless component because the function component is only used to define the variable work on the simple task. State is only used in the class component.

But now through the React Hooks, we can use state in function component but compatibility class component is better than function component.

What are the differences between props and state?

Props are used to pass the data while the state is used for manipulate the data and manage the data. Props only read the data while state modified the data and it's modified by its own component another component can’t be accessed by from outside. Props used attribute and value to pass the data while state used state() method.

          condition    Props State
State can be mutable No Yes
We can set default value inside the component Yes Yes
We can change inside component No Yes
Follow uni-direction Yes No
Can change by parent component Yes No
Used function component No No
It can be change in child component Yes No
Can set default value Yes Yes
 

Planning to Hire Mobile App Development Company ?

Your Search ends here.

 

Full development example of props and state


import React, { Component } from &amp;#39;react&amp;#39;;

export default class FormDataComponent extends Component {

    userData;

    constructor(props) {
        super(props);

        this.onChangeName = this.onChangeName.bind(this);
        this.onChangeEmail = this.onChangeEmail.bind(this);
        this.onChangePhone = this.onChangePhone.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            name: &amp;#39;&amp;#39;,
            email: &amp;#39;&amp;#39;,
            phone: &amp;#39;&amp;#39;
        }
    }

    // Form Events
    onChangeName(e) {
        this.setState({ name: e.target.value })
    }

    onChangeEmail(e) {
        this.setState({ email: e.target.value })
    }

    onChangePhone(e) {
        this.setState({ phone: e.target.value })
    }

    onSubmit(e) {
        e.preventDefault()

        this.setState({
            name: &amp;#39;&amp;#39;,
            email: &amp;#39;&amp;#39;,
            phone: &amp;#39;&amp;#39;
        })
    }

    // React Life Cycle
    componentDidMount() {
        this.userData = JSON.parse(localStorage.getItem(&amp;#39;user&amp;#39;));

        if (localStorage.getItem(&amp;#39;user&amp;#39;)) {
            this.setState({
                name: this.userData.name,
                email: this.userData.email,
                phone: this.userData.phone
            })
        } else {
            this.setState({
                name: &amp;#39;&amp;#39;,
                email: &amp;#39;&amp;#39;,
                phone: &amp;#39;&amp;#39;
            })
        }
    }

    componentWillUpdate(nextProps, nextState) {
        localStorage.setItem(&amp;#39;user&amp;#39;, JSON.stringify(nextState));
    }

    render() {
        return (<div classname="container"><form onsubmit="{this.onSubmit}"><div classname="form-group">
                        <label>Name</label>
                        <input classname="form-control" onchange="{this.onChangeName}" type="text" value="{this.state.name}" /></div>
<div classname="form-group">
                        <label>Email</label>
                        <input classname="form-control" onchange="{this.onChangeEmail}" type="email" value="{this.state.email}" /></div>
<div classname="form-group">
                        <label>Phone</label>
                        <input classname="form-control" onchange="{this.onChangePhone}" type="tel" value="{this.state.phone}" /></div><button classname="btn btn-primary btn-block" type="submit">Submit</button></form></div>
        )
    }
}

Conclusion

In this blog, what we have learned is about props and state with examples for each. We have also discussed the task and their purposes. How they are different from each other and in what way they are similar. We also discussed their performance and compatibility. Through this practical blog, you will get a complete idea about all these topics.

A complete guide on React fundamentals: Props and State A complete guide on React fundamentals Props and State

Table of Content

Introduction

When we talk about State and Props, both are considered as variables, but they work for different tasks and purposes. To manage the structure of reacting data props can only pass it by using unidirectional from parent component to child.

What are props?

Props are defined in the parent component as variable and pass the value to the child component. Normally we familiar with C and C++ we define the variable before we must declare the variable. Same as it props are declared on one component (parent) and define in another component(child). Props follow the uni-directional flow (from parent component to child component). We can say that props are read-only components because it just assigns a value and passes the value as parameter.

How to declare props?

Here Details are child component which is imported in a parent component


Title its props attribute and my first props are props value


We can also pass the array as props using list

     const value= [1, 2, 3, 4, 5];


How to pass the value?

Props are normally used for the set the internal which is based on props value which we define in constructor like that.


 class Details extends React.Component {
  constructor(props) {
    super(props)
    console.log(props.title)
  }
}


We can directly assign in the render method


 render {
 return (<div><h2>Suject details:</h2>
<h2>{this.props.title}</h2></div>
      )
}

Props never change the value it only passes the value. Props also used to allow the child component to access the method In the parent component. There is a good way to manage the state in the parent component. Every time component will display some kind of information which is based on the props.

 
Parent Component

import &amp;#39;./App.css&amp;#39;;
import React from &amp;#39;react&amp;#39;;
import Details from &amp;#39;./Details&amp;#39;;


class Footer extends React.Component
 {

    render()
    {             
    var person =
     {
      sub1: &amp;#39;Java&amp;#39;,
      sub2: &amp;#39;php&amp;#39;,
      sub3:&amp;#39;React&amp;#39;
     };

     const value= [1, 2, 3, 4, 5];

    
     return (<div classname="">
          {/* Details component which accepts props */}<details title="my first props"></details></div>
      );
  
        
  }
    
}
export default Footer;


Child Component
import React, { } from 'react';
  
class Details extends React.Component 
{
  render() 
  {
Const {sub1,sub2,sub3}={...this.props};/// expmple of sperad and rest 
const {a}={...this.props.item}

   return(      

Suject details:

{this.props.item}

{this.props.title}

  1. sub1:{sub1}
  2. sub2:{sub2}
  3. sub3:{sub3}
) }

What is State?

The state is mange the data it can change the data while props never change the data state even set the state of data when we perform any event like button click or input change event we have to set the state of data that time state performs their task for managing the overall data.

How To Update a Component’s State?

State can not be modified directly we have to modify with a special method called setstate()

        this.setState=name:’rahi’     //wrong        
        this.setState({name: ‘rahi’})    //right


What happens when the state changes?

The state will be changed depending on the input when the time input changes then the event will be triggered and that time state is rendered and the state collects the initial value of the state. When the state change reacts then it takes the all information immediately and re-render the DOM only which component gets an update in the state, and that’s why it react faster.

Can we use state in every component?

There are two components, one is the functional component and the second is the class component. The function is also called the stateless component because the function component is only used to define the variable work on the simple task. State is only used in the class component.

But now through the React Hooks, we can use state in function component but compatibility class component is better than function component.

What are the differences between props and state?

Props are used to pass the data while the state is used for manipulate the data and manage the data. Props only read the data while state modified the data and it's modified by its own component another component can’t be accessed by from outside. Props used attribute and value to pass the data while state used state() method.

          condition    Props State
State can be mutable No Yes
We can set default value inside the component Yes Yes
We can change inside component No Yes
Follow uni-direction Yes No
Can change by parent component Yes No
Used function component No No
It can be change in child component Yes No
Can set default value Yes Yes
 

Planning to Hire Mobile App Development Company ?

Your Search ends here.

 

Full development example of props and state


import React, { Component } from &amp;#39;react&amp;#39;;

export default class FormDataComponent extends Component {

    userData;

    constructor(props) {
        super(props);

        this.onChangeName = this.onChangeName.bind(this);
        this.onChangeEmail = this.onChangeEmail.bind(this);
        this.onChangePhone = this.onChangePhone.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        this.state = {
            name: &amp;#39;&amp;#39;,
            email: &amp;#39;&amp;#39;,
            phone: &amp;#39;&amp;#39;
        }
    }

    // Form Events
    onChangeName(e) {
        this.setState({ name: e.target.value })
    }

    onChangeEmail(e) {
        this.setState({ email: e.target.value })
    }

    onChangePhone(e) {
        this.setState({ phone: e.target.value })
    }

    onSubmit(e) {
        e.preventDefault()

        this.setState({
            name: &amp;#39;&amp;#39;,
            email: &amp;#39;&amp;#39;,
            phone: &amp;#39;&amp;#39;
        })
    }

    // React Life Cycle
    componentDidMount() {
        this.userData = JSON.parse(localStorage.getItem(&amp;#39;user&amp;#39;));

        if (localStorage.getItem(&amp;#39;user&amp;#39;)) {
            this.setState({
                name: this.userData.name,
                email: this.userData.email,
                phone: this.userData.phone
            })
        } else {
            this.setState({
                name: &amp;#39;&amp;#39;,
                email: &amp;#39;&amp;#39;,
                phone: &amp;#39;&amp;#39;
            })
        }
    }

    componentWillUpdate(nextProps, nextState) {
        localStorage.setItem(&amp;#39;user&amp;#39;, JSON.stringify(nextState));
    }

    render() {
        return (<div classname="container"><form onsubmit="{this.onSubmit}"><div classname="form-group">
                        <label>Name</label>
                        <input classname="form-control" onchange="{this.onChangeName}" type="text" value="{this.state.name}" /></div>
<div classname="form-group">
                        <label>Email</label>
                        <input classname="form-control" onchange="{this.onChangeEmail}" type="email" value="{this.state.email}" /></div>
<div classname="form-group">
                        <label>Phone</label>
                        <input classname="form-control" onchange="{this.onChangePhone}" type="tel" value="{this.state.phone}" /></div><button classname="btn btn-primary btn-block" type="submit">Submit</button></form></div>
        )
    }
}

Conclusion

In this blog, what we have learned is about props and state with examples for each. We have also discussed the task and their purposes. How they are different from each other and in what way they are similar. We also discussed their performance and compatibility. Through this practical blog, you will get a complete idea about all these topics.