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:
xxxxxxxxxx
1
const Tag = 'div'; // <----------- tag name from varaible
2
3
const element = (
4
<Tag>Some content inside ...</Tag>
5
);
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:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const MyComponent = (props) => {
6
const DynamicTag = `h${props.priority}`; // <----------- dynamic tag name
7
return <DynamicTag>priority = {props.priority}</DynamicTag>;
8
};
9
10
const App = () => {
11
return (
12
<div>
13
<MyComponent priority="1" />
14
<MyComponent priority="2" />
15
<MyComponent priority="3" />
16
</div>
17
);
18
};
19
20
const root = document.querySelector('#root');
21
ReactDOM.render(<App />, root );
Note:
If you are using TypeScript replece line with
const DynamicTag = ...
with:xxxxxxxxxx
1const DynamicTag = `h${this.props.priority}` as keyof JSX.IntrinsicElements;