Dynamic tag name in jsx and React

No way to do that in-place, just put it in a variable (with first letter capitalised):

const CustomTag = `h${this.props.priority}`;

<CustomTag>Hello</CustomTag>

If you're using TypeScript, you'll have seen an error like this:

Type '{ children: string; }' has no properties in common with type 'IntrinsicAttributes'.ts(2559)

TypeScript does not know that CustomTag is a valid HTML tag name and throws an unhelpful error.

To fix, cast CustomTag as keyof JSX.IntrinsicElements!

const CustomTag = `h${this.props.priority}` as keyof JSX.IntrinsicElements;

<CustomTag>Hello</CustomTag>

For completeness, if you want to use a dynamic name, you can also directly call React.createElement instead of using JSX:

React.createElement(`h${this.props.priority}`, null, 'Hello')

This avoids having to create a new variable or component.

With props:

React.createElement(
  `h${this.props.priority}`,
  {
    foo: 'bar',
  },
  'Hello'
)

From the docs:

Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span'), or a React component type (a class or a function).

Code written with JSX will be converted to use React.createElement(). You will not typically invoke React.createElement() directly if you are using JSX. See React Without JSX to learn more.

Tags:

Reactjs

Jsx