Reassign Destructed Values
Our component ended up in a weird place yesterday.
let Greeting({ As, name }) {
return <As>Hello {name}</As>
}
The capitalized As
prop stands out. The capitalization is important to make the JSX transformer evaluate As
as an expression. However, the capitalized attribute looks strong when used:
Fortunately, JavaScript has a destructuring assignment syntax that allows us to do two things at once:
- receive as, as a lowercase prop
- assign as’s value to a new
As
variable, capitalized for JSX evaluation
Using a colon — where we unpack props — the new assignment looks like this: { as: As }
Here it is in context of our component declaration:
function Greeting({ as: As, name }) {
return <As>Hello {name}</As>;
}
Take it home
When we assign object properties to new variable names, we can name them whatever we want. Open this CodeSandbox and toy with the re-assignment syntax. Try Component, Tag, or anything else you like. This is a local variable. So there’s no “wrong” way to do it. While you’re there, what happens if we don’t supply an as prop? Where can we provide a sensible default?