0

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".
zero298
  • 25,467
  • 10
  • 75
  • 100
Viking
  • 21
  • 1
  • Yes, it is, but it only works if `randomName` was a property of the object that `useParams()` returns. If it isn't, it doesn't work. I'm not clear on your question. What do mean "same property name"? – zero298 Oct 09 '20 at 14:57
  • Thanks for the help, means a lot. 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". – Viking Oct 09 '20 at 15:37
  • If you are looking to get all the params from useParams() with a random name, using deconstructing. You can use {...anyNameYouWant} = useParams() then you can use anyNameYouWant.map(param=>console.log(param)) The triple period is the spread operator. – Sir Codes Alot Oct 09 '20 at 15:55

2 Answers2

1

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().

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
0

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.

jperl
  • 4,662
  • 2
  • 16
  • 29