Tanvir
Tanvir

Reputation: 1673

How to Object destructuring in child component in REACT

What is the problem with Object destructuring in REACT here? Check the CODEPEN HERE The same destructuring works outside React. How can I send object as an argument and have a parameterized destructure in the child component?

const MyComponent= ({name,age})=> { 
    return (
      <div>
        <h1> HI THERE I M {name}</h1>
      </div>
    );
}  


function App() {

  let person = { name: "ALEN", age : 40};
  return (
    <div>
      <MyComponent person={person} />
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector("#root"));

Upvotes: 1

Views: 1248

Answers (2)

Amruth
Amruth

Reputation: 5912

You are getting person in props, not name and age, you can follow like this.

First destruct person from props then destruct name and age from person.

const MyComponent = ({ person }) => {
const { name, age } = person;
  return (
    <div>
      <h1> HI THERE I M {name}</h1>
    </div>
  );
};

Upvotes: 1

Tobias S.
Tobias S.

Reputation: 23885

React will pass an object down to MyComponent that looks like this:

{ person: { name: "ALEN", age: 40 } }

Because you specify the properties name and age in your object destructuring and not person, it will be undefined.

You can declare the function like this:

const MyComponent = ({ person: { name,age } }) => { 
    return (
      <div>
        <h1> HI THERE I M {name}</h1>
      </div>
    );
}

Upvotes: 5

Related Questions