Reputation: 3
I'm building a simple slide-deck web app that uses a JSON object as a mock database, and I'm rendering the UI via ReactJS components.
Is there a way to store the HTML + markup in the JSON object as a string, pass the string to ReactJS, and then have ReactJS render the HTML elements/markup in a React Component?
Here is an example of the JSON object:
{
"slides": {
"1":{
"title":"Introductory Finance",
"content":"<p>By Raymond Arthur</p>"
}
}
}
This is the React component:
class Body extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div className='body'>
{this.props.content}
</div>
);
}
}
At the moment, if I pass slides[1].title.content
as a prop to a React Component with a <div>
, <p>By Raymond Arthur</p>
is being rendered as text on the screen (i.e. React is not actually creating <p></p>
elements with text inside them). It's as though React is escaping the <p>By Raymond Arthur</p>
as a text string instead of recognising the HTML markup/elements.
How can I fix this? How can I store HTML + markup as a string in a JSON object or a database, serve the HTML + markup string to ReactJS, and then get ReactJS to recognise that it is HTML and not just a string?
I have seen other SF threads referencing dangerouslySetInnerHTML
- is this the only option?
Or ReactDOMServer?
Upvotes: 0
Views: 295
Reputation: 999
To solve this you can use dangerouslySetInnerHTML attribute something like this.It will wrap your markup which is a object property into specified div Tag below.
<div dangerouslySetInnerHTML={{__html:this.props.content}}></div>
Upvotes: 1