Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 623
Greg Avatar asked Sep 08 '16 17:09

Greg


3 Answers

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

        },
like image 65
steveinatorx Avatar answered Nov 06 '22 14:11

steveinatorx


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.

like image 6
Kev Avatar answered Nov 06 '22 14:11

Kev


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>
)
like image 3
ThisIsWilliam Avatar answered Nov 06 '22 14:11

ThisIsWilliam