0

I am trying to render HTML from JSON into my React component. I am aware of the dangerouslySetInnerHTML and am not looking to use that as I would like to leverage other React components inside of the rendered HTML. Currently I can render any element as long as I close the tag. But this is not the case as in if I would like to put multiple elements or img tags in a div i would need it to remain open until all of the img tags have completed. I would appreciate any help on this. Thanks

 render(){ var data = [ { type: 'div', open: true, id: 1, className: 'col-md-12 test', value: '' }, { type: 'div', open: false, id: 1 } ] var elements = data.map(function(element){ if(element.open){ return <element.type className={element.className}> } else { return </element.type> } }) return ( <div> {elements} </div> ) } 

webpack error

 3 | return <element.type className={element.className}> 34 | } else { > 35 | return </element.type> | ^ 36 | } 37 | }) 38 | return ( @ ./src/index.js 9:11-38 
2
  • React doesn't render HTML, it renders DOM elements. You either need to build HTML and inject it as a string or build elements programmatically; the approach you're taking isn't the React Way. Perhaps you should state the problem you're trying to solve, and we can give you a more Reactish way to do things. Commented Oct 7, 2016 at 3:45
  • I am working on an HTML editor in react. I need to be able to add and store each element on a page. Commented Oct 7, 2016 at 4:50

3 Answers 3

1

The data structure is redundant; you can simply do this:

render() { var elements = ( <div id='1' className='col-md-12 test'></div> ); return ( <div>{elements}</div> ); } 

Element trees themselves are just data. Rather than trying to invent a data structure to represent one, just use JSX.

Sign up to request clarification or add additional context in comments.

3 Comments

"redundant extra" is redundant
I need to keep the opening and closing tag separate this way I can insert elements in between the tags
You can use a JSX variable between the open & close tags as well.
0

The closing tag wasn't proper.

check the following fiddle.

https://jsfiddle.net/pranesh_ravi/mLoL6pzz/

Hope it helps!

Comments

0

I think @pranesh answered right. It has to go something like this

var elements = data.map(function(element){ if(element.open){ return <element.type className ={element.className}>Sample</element.type> } else { return <element.type>Sample</element.type> } }) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.