Render Element by Tag Name in React

19 March 2021

Updated: 03 September 2023

When using React it can sometimes be useful to render a standard HTML element given the element name dynamically as a prop

React allows us to do this provided we store the element name in a variable that starts with a capital letter, as JSX requires this to render a custom element

We can do something like this by defining a generic element in React which just takes in the name of the tag in addition to it’s usual props and children, something like this:

1
const GenericElement = ({ tagName: Tag, children, ...innerProps }) => (
2
<Tag {...innerProps}>{children}</Tag>
3
)

We can then render this element by calling the GenericElement with the tagName prop and then any children we’d like:

1
<GenericElement tagName="h1">I am an h1</GenericElement>

Here’s a short example using Replit for reference, all the important stuff is in the src/App.jsx file: