Inject Components
Below is the first example on reacts.org. It shows the interplay of functions, JavaScript, JSX, and HTML that makes React unique.
let Greeting({ name }) { return <div>Hello {name}</div> }
It also demonstrates a big omission in the design of JSX.
JSX doesn’t have a syntax for rendering custom components with an alternate host element. Specially, this component will always render as a div
— excluding it from inline use.
It’d be nice to tell React “render Greeting but as a span.”
There’s no first class JSX syntax for that. But React, JSX, and a bit of JS trickery make this possible in our own code. Use what we’ve learned about JS expressions to inject the desired component by passing it in as a prop.
<Greeting As="span" />
Of course custom components can be injected as well.
<Greeting as={MyFancyDiv} />
Here’s what this pattern looks like as a component declaration:
let Greeting({ As, name }) {
return <As>Hello {name}</As>
}
Take it Home
There’s something kinda funny about this As
prop we’ve made. That funny thing is because of a JSX heuristic we learned about earlier. Can you put your finger on it? Can you change it to make it more natural? Explore in this CodeSandbox.