April 30, 2025

Destructing Props and State in React

Destructing is a ES6 features that make to unpack array of values and property from object into distinct variables. In react destructing props and state improves read code availability.

Functional Component

App.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import Destructuring from './Destructuring';
 
 const App = () =>{
   return (
     <div>
     <Destructuring name="Vishvjeet" rollNo={123456} />
     </div>
   )
 }

render(<App />, document.getElementById('root'));

Destructuring.js

import React from 'react';

const Destructuring = (props) => {
    return (
        <div>
            Hello <strong>{props.name}</strong> your Roll No is <strong>{props.rollNo}</strong>
        </div>
    );
};

export default Destructuring;

Destructuring.js (1st way)
Destructing in the parameter with curly braces { }

import React from 'react';
const Destructuring = ({name, rollNo}) => {
    return (
        <div>
            Hello <strong>{name}</strong> your Roll No is <strong>{rollNo}</strong>
        </div>
    );
};
export default Destructuring;

Destructuring.js (2nd way)
Destructing with the function body

import React from 'react';

const Destructuring = (props) => {
const {name, rollNo} = props
    return (
        <div>
            Hello <strong>{name}</strong> your Roll No is <strong>{rollNo}</strong>
        </div>
    );
};

export default Destructuring;

Demo

Class Component

Destructuring.js
Destructing method in class component we generally inside render method

import React, { Component } from 'react';

class Destructuring extends Component {
    render(props) {
        const {name, rollNo} = this.props
        return (
            <div>
                Hello {name} your Roll No is {rollNo}
            </div>
        );
    }
}

export default Destructuring;

Demo

State

Same thing as we’ve done with props we can do with state

const {name, rollNo} = this.state

 

Leave a Reply

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