kbrk
kbrk

Reputation: 660

String to React DOM object

I'm using react js 15.4.2. I have html data stored as string like "<p>Hello..</p>". I can not append them to the DOM.

...
componentDidMount(){
  let obj = dataFromDB.map((data)=>{
               return(
                  <div>
                    {data.strHtml}
                  </div>
               ) 
            }) 
   this.setState({storedObj: obj})
}

render(){
    return(
      <div>
          {this.state.storedObj}
      </div>
    )
}
...

Do you have any suggestions to append the html objects to the DOM properly ?

Upvotes: 4

Views: 4336

Answers (2)

radlaz
radlaz

Reputation: 318

you could also look into react-html-parser module for parsing html before rendering to the DOM it's pretty easy to use.

import Parser from 'html-react-parser';    

class Example extends React.Component {

render() {
   return (
     <div>
       {Parser(this.state.dataStored)}
     </div>
   )
}
}

Upvotes: 6

Ihor Skliar
Ihor Skliar

Reputation: 390

You should use this code -

  return <div dangerouslySetInnerHTML={{__html: data.strHtml}} />;

Upvotes: -1

Related Questions