Languages
[Edit]
EN

React - how to create dynamic tag name

0 points
Created by:
christa
600

In this article, we would like to show you how to create a dynamic tag name in React.

Quick solution:

const Tag = 'div';  // <----------- tag name from varaible

const element = (
    <Tag>Some content inside ...</Tag>
);

 

Practical example

Below we create a component that receives heading importance as priority via props and returns<h1>, <h2> or <h3> tag depending on received props.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const MyComponent = (props) => {
  const DynamicTag = `h${props.priority}`;  // <----------- dynamic tag name
  return <DynamicTag>priority = {props.priority}</DynamicTag>;
};

const App = () => {
  return (
    <div>
      <MyComponent priority="1" />
      <MyComponent priority="2" />
      <MyComponent priority="3" />
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Note:

If you are using TypeScript replece line with const DynamicTag = ... with:

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

Alternative titles

  1. React - how to create React element using variable with tag name
  2. React - create simple element using tag from variable
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join