Skip to content
Advertisement

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 the Babel plugin to compile JSX.

Advertisement

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>
    );
},
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement