Home » Reactjs » Dynamic tag name in jsx and React

Dynamic tag name in jsx and React

Posted by: admin November 30, 2017 Leave a comment

Questions:

I try to write a React component. for html heading tags(h1,h2,h3,etc…), where the heading priority dynamically changing based on the priority we have defined in the props.

Here what I try to do.

<h{this.props.priority}>Hello</h{this.props.priority}>

expected output:

<h1>Hello</h1>

This is not working. Is there any possible method to do this?

Answers:

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 >

Questions:
Answers:

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.