JSX with HTML tag from variable

I have a React component defined in JSX that returns a cell using either td or th , for example:

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

Is it possible to write JSX in such a way that the HTML tag is taken from a variable? How:

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

The above code returns an unexpected token error indicating { . I am using webpack with the babel plugin to compile JSX.

+5
source share
2 answers

Try adjusting the state of the component and its rendering as follows:

 render: function() { return( <this.state.tagName {...myProps}> <div className="some-class">some content</div> </this.state.tagName> ); }, 
+6
source

You can do something like:

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

Please note that this does not really solve your question about the “dynamic tag”, but rather about the problem that you seem to have.

+5
source

All Articles