A polymorphic as prop
A heading, a paragraph, and a label can share one look but need different tags.
Instead of a component per tag, give the component an as prop that names the
element to render, and type it as ElementType:
import type { ElementType, ReactNode } from 'react';
interface TextProps {
as?: ElementType;
children: ReactNode;
}
function Text({ as: Component = 'p', children }: TextProps) {
return <Component>{children}</Component>;
}
ElementType is any component or intrinsic tag name, so as accepts 'h1',
'p', or a component you wrote. Destructuring it as Component with a capital
letter is required — JSX treats a lowercase tag as a literal HTML element and a
capitalised one as a variable. The = 'p' default means a Text with no as
renders a paragraph.
At the call site the prop reads like a tag name:
<Text as="h1">Hello</Text>
Text renders an <h1>, and the same component renders a <p> elsewhere. A
fully typed as can also carry that element's props; this version names the
element and leaves the rest to the caller.
Your job is to give a component a typed as prop in App.tsx.
Challenge
A component should render the tag its caller names, not a fixed one. Export an
App component from App.tsx that renders a Text component with as="h1"
around the text Hello. Text takes an optional as prop typed as
ElementType, defaults it to 'p', and renders its children with that tag.
The Test renders your component and looks for an h1 reading Hello. The
starter renders a paragraph, so the Test fails.