2

I am using Context API to pass items from one component to another. I am destructuring items as one would do:

const { smallPrice, bigPrice } = useContext(Context)

I wondered if it would be possible to destructure them with interpolated strings, so that I can use the props.id from the component.

const { `smallPrice${props.id}`, `bigPrice${props.id}` } = useContext(Context)

This won't work however. Are there any alternatives to destructure things coming from context with interpolated strings?

uber
  • 4,163
  • 5
  • 26
  • 55
  • 2
    You could use computed property names, but you'd have to declare static target variables anyway. No, don't do this. – Bergi Apr 06 '20 at 15:52
  • Yeah, I'd recommend storing your `smallPrice` and `bigPrice` values in an array or object and access them that way. – Barry Michael Doyle Apr 06 '20 at 15:53

1 Answers1

1

You can do this by using destructuring assignment. You reference the variable by a key and assign it to a known variable name. Example:

const {
  [`smallPrice${props.id}`]: smallPrices,
  [`bigPrice${props.id}`]: bigPrices
} = useContext(Context);

console.log(smallPrices);
console.log(bigPrices);
Teddy Sterne
  • 13,774
  • 2
  • 46
  • 51