I have a React component defined in JSX which returns a cell using either td
or th
, e.g.:
JavaScript
x
14
14
1
if(myType === 'header') {
2
return (
3
<th {myProps}>
4
<div className="some-class">some content</div>
5
</th>
6
);
7
}
8
9
return (
10
<td {myProps}>
11
<div className="some-class">some content</div>
12
</td>
13
);
14
Would it be possible to write the JSX in such a way that the HTML tag is taken from a variable? Like:
JavaScript
1
7
1
let myTag = myType === "header" ? 'th' : 'td';
2
return (
3
<{myTag} {myProps}>
4
<div className="some-class">some content</div>
5
</{myTag}>
6
);
7
The above code returns an error:
“unexpected token” pointing at
{
.
I am using Webpack with the Babel plugin to compile JSX.
Advertisement
Answer
Try setting your component state and rendering like so:
JavaScript
1
8
1
render: function() {
2
return(
3
<this.state.tagName {myProps}>
4
<div className="some-class">some content</div>
5
</this.state.tagName>
6
);
7
},
8