0

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?

2
  • 1
    If you want to avoid dangerouslySetInnerHTML, you can use the package react-html-parser Commented Jul 3, 2021 at 4:04
  • Thank you, I'll check out the package, Commented Jul 3, 2021 at 7:42

1 Answer 1

1

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>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.