Detuned Detuned - 1 year ago 123
React JSX Question

Interpolate a dynamic HTML element in React

I have the following

contract which gets passed down to certain components that basically iterate over the format and render the data inside of
elements. However, I'd like the ability to set a custom HTML element instead of the default
element used.

What are some good techniques for achieving this?

For example:

// from
const data = [{ text: 'hello' }, { text: 'world' }];
// to
const data = [{ text: 'hello', element: 'span' }, { text: 'world', element: 'h1' }];

Basically iterates over each item in the array and uses their custom HTML element to render the text. I know one can achieve this by using React's non JSX syntax, however, these components are quite complex, so I'd ideally like to use JSX. Any thoughts? Maybe there's a way to combine the two (use non JSX for the custom elements and within them use JSX?

Answer Source

Map use of React.createElement() function inside a map like React.createElement(item.element, null, item.text)

class App extends React.Component {
    this.state= {
      data : [{ text: 'hello', element: 'span' }, { text: 'world', element: 'h1' }]
  render() {
    return (
        { {
          return (React.createElement(item.element, null, item.text)) 

ReactDOM.render(<App/>, document.getElementById('app'));
<script src=""></script>
<script src=""></script>
<div id="app"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download