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"));
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>
);
}
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>
);
};