javascriptnode.jsreactjsjsx

Dynamic tag name in React JSX


I am trying to write a React component for HTML heading tags (h1, h2, h3, etc.), where the heading level is specified via a prop.

I tried to do it like this:

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

And I expected output like:

<h1>Hello</h1>

But this is not working.

Is there any way to do this?


Solution

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

    const CustomTag = `h${this.props.level}`;
    
    <CustomTag>Hello</CustomTag>