Detuned Detuned - 1 month ago 36
React JSX Question

Interpolate a dynamic HTML element in React

I have the following

JSON
contract which gets passed down to certain components that basically iterate over the format and render the data inside of
p
elements. However, I'd like the ability to set a custom HTML element instead of the default
p
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

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

class App extends React.Component {
  constructor(){
    super();
    this.state= {
      data : [{ text: 'hello', element: 'span' }, { text: 'world', element: 'h1' }]
    }
  }
  render() {
    
    return (
      <div>
        {this.state.data.map(function(item) {
          return (React.createElement(item.element, null, item.text)) 
        })}
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>