Dynamic tag name in jsx and React

I am trying to write a React component. for html headers (h1, h2, h3, etc.), where the priority of the header dynamically changes depending on the priority that we have defined in the details.

Here is what I am trying to do.

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

expected output:

<h1>Hello</h1>

This does not work. Is there any possible way to do this?

+113
react-jsx
Nov 02 '15 at 6:26
source share
3 answers

There is no way to do this in place, just put it in a variable ( with a capital first letter ):

 const CustomTag = 'h${this.props.priority}'; <CustomTag>Hello</CustomTag> 
+231
Nov 02 '15 at 6:31
source share

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 eliminates the need to create a new variable or component.

With the requisite:

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



From the docs :

Create and return a new React element of this type. A type argument can be either a tag name string (for example, 'div' or 'span' ) or a React component type (class or function).

Code written using JSX will be converted to use React.createElement() . Usually you will not call React.createElement() directly if you use JSX. See React Without JSX for more.

+17
Aug 21 '17 at 2:27 on
source share

In the case of dynamic headers (h1, h2 ...), the component can return React.createElement (mentioned above by Felix ), as it happens.

 const Heading = ({level, children, ...props}) => { return React.createElement('h${level}', props , children) } 

For the arrangement, both details and children are skipped.

See an example

+2
Jun 14 '18 at 21:51
source share



All Articles