Amiramix Amiramix - 2 months ago 14
React JSX Question

JSX with a HTML tag from a variable

I have a React component defined in JSX which returns a cell using either

td
or
th
, e.g.:

if(myType === 'header') {
return (
<th {...myProps}>
<div className="some-class">some content</div>
</th>
);
}

return (
<td {...myProps}>
<div className="some-class">some content</div>
</td>
);


Would it be possible to write the JSX in such a way that the HTML tag is taken from a variable? Like:

let myTag = myType === "header" ? 'th' : 'td';
return (
<{myTag} {...myProps}>
<div className="some-class">some content</div>
</{myTag}>
);


The above code returns an error "unexpected token" pointing at
{
. I am using webpack with a babel plugin to compile JSX.

Answer

Try setting your component state and rendering like so:

render: function() {

            return(
                <this.state.tagName {...myProps}>
                  <div className="some-class">some content</div>
                </this.state.tagName>
            );

        },
Comments