Greg
Greg

Reputation: 8340

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.

Upvotes: 13

Views: 18822

Answers (3)

steveinatorx
steveinatorx

Reputation: 745

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>
    );
},

Upvotes: 12

ThisIsWilliam
ThisIsWilliam

Reputation: 1095

The first answer did not work for my case so I solved it in another way. From React documentation each element converts to pure JS like this.

So it is possible to create elements for React component that are dynamic like this:

let myTag = myType === "header" ? 'th' : 'td';

React.createElement(
  myTag,
  {className: 'some-class'},
  <div className="some-class">some content</div>
)

Upvotes: 3

Kev
Kev

Reputation: 5442

You can do something like:

const content = <div> some content </div>
return (
  {myType === 'header'
    ? <th>{content}</th>
    : <td>{content}</td>
  }
)

Note that this does not really solve your question about "dynamic tag" but rather the problem you seem to have.

Upvotes: 6

Related Questions