how is it possible that we can destructe an object using any property name in React?

651 views Asked by At

I have a doubt can any body help me with my doubt or can any one tell me where I can find my answer?

So as we know in object destructing we must use the same property name to destructure. However, in React when we destructure useParams from react-router-dom we use any random property name. example const {randomName} = useParams() is this not destructing?

By same property name I meant this:

const person = { name: "jon", age: 32, location: "UK", }; 
const { name } = person; 
const { abc } = person; 
console.log(name); // logs - jon 
console.log(abc);// logs - undefined 
//(since we did not use the same property name as "name".
2

There are 2 answers

0
jperl On

const { name } = person; is equivalent to const name = person.name. If person has no name property, person.name will as expected return undefined and so will const { name } = person;, too.

2
Daniel Beck On

useParams() returns an object containing all the parameters defined in the URL; when you destructure that you're not using "any random property name", you use the parameters defined in the URL.

const {randomName} = useParams() will be undefined if randomName is not one of the URL parameters returned by useParams().