EN
React - how to create dynamic tag name
0
points
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;