Create New Post

React - ES6 Destructuring

Destructuring assignment is a powerful feature in ES6 that allows you to extract values from arrays or properties from objects and assign them to variables in a more concise way. In the context of React, destructuring is commonly used to simplify the extraction of values from props and state. Here are some examples of how destructuring can be used in React:

  1. Destructuring Props:

    // Without destructuring
    const MyComponentWithoutDestructuring = (props) => {
    return <div>{props.name}</div>;
    };

    // With destructuring
    const MyComponentWithDestructuring = ({ name }) => {
    return <div>{name}</div>;
    };

  2. Destructuring State:

    // Class component without destructuring
    class MyClassComponentWithoutDestructuring extends React.Component {
    render() {
    const { stateValue } = this.state;
    return <div>{stateValue}</div>;
    }
    }

    // Class component with destructuring
    class MyClassComponentWithDestructuring extends React.Component {
    render() {
    const { stateValue } = this.state;
    return <div>{stateValue}</div>;
    }
    }

  3. Destructuring Arrays:

    const MyArrayComponent = () => {
    const myArray = [1, 2, 3];

    // Without destructuring
    const firstValueWithoutDestructuring = myArray[0];

    // With destructuring
    const [firstValueWithDestructuring] = myArray;

    return (
    <div>
    <p>First Value Without Destructuring: {firstValueWithoutDestructuring}</p>
    <p>First Value With Destructuring: {firstValueWithDestructuring}</p>
    </div>
    );
    };

  4. Destructuring Nested Objects:

    const MyNestedObjectComponent = () => {
    const user = {
    name: 'John',
    address: {
    city: 'New York',
    country: 'USA',
    },
    };

    // Without destructuring
    const cityNameWithoutDestructuring = user.address.city;

    // With destructuring
    const { address: { city: cityNameWithDestructuring } } = user;

    return (
    <div>
    <p>City Without Destructuring: {cityNameWithoutDestructuring}</p>
    <p>City With Destructuring: {cityNameWithDestructuring}</p>
    </div>
    );
    };

Comments

Leave a Reply

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

22552