regina_fallangi
regina_fallangi

Reputation: 2198

ReacjJS: Parse HTML from strings and use it

I have a JSON questions.json:

{
  "question1": "This is a <strong>cool</strong> question"
}

In my App.js I do:

import questions from './questions.json'

class App {
  render () {
    return (
        <p>{questions["question1"]}</p>
    )
  }

That displays:

"This is a < strong> cool < /strong> question"

(Notice I escaped "<\strong>" because SO would render "bool" bold otherwise.)

instead of

"This is a cool question"

I can think of writing a recursion that finds each "strong" markup, but I am wondering if a way already exists.

Thanks

Upvotes: 0

Views: 48

Answers (2)

Andy
Andy

Reputation: 63550

Here's a working example using dangerouslySetInnerHTML.

const questions = {
  question1: 'This is a <strong>cool</strong> question'
};

class App extends React.Component {
  render () {
    return (
      <p dangerouslySetInnerHTML={{__html: questions['question1']}} />
    );
  }
}

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Upvotes: 1

Chithambara Kumar
Chithambara Kumar

Reputation: 926

You can try using dangerouslySetInnerHTML and check if it works.

 <p dangerouslySetInnerHTML={{ __html: questions["question1"] }} />

Upvotes: 0

Related Questions