Render a React component as any HTML element

If you’ve created a React component, you will probably have come across a scenario where you want it to be rendered as different HTML tags on different pages.

Say you’ve created a component to output headings, you might want to render it as an h1 or an h2.

Here’s how you’d do the component.

export function MyHeadingComponent({ as: Component = "h2", children }) {
	return (
		<Component>
			{children}
		</Component>
	)
}

And here’s how to use it.

<MyHeadingComponent as="h1">
	The Heading Content
</MyHeadingComponent>

Don’t worry if you forget to add the as prop, it’ll be h2 by default.

Share