2

How can I convert in JavaScript/ReactJS into string.
For example I have an object:

{
  article: '<p class="md-block-unstyled">First text...</p><p>Second text></p>'
} 

I want to convert it and render a paragraph:

First Text... Second text

I don't want the <p> tag or any others tag to be printed on the screen but I want them to behave as actual paragraphs.

Tryliom
  • 895
  • 1
  • 12
  • 37
Dgen Vnk
  • 43
  • 3

2 Answers2

3

You can use dangerouslySetInnerHTML to render HTML from a string.

Example

function App() {
  const obj = {
    article: '<p class="md-block-unstyled">First text...</p><p>Second text</p>'
  };
  return <div dangerouslySetInnerHTML={{ __html: obj.article }} />;
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • 1
    Thanks you! But I would like to do it without using dangerouslySetInnerHTML. There is no other option to do it ? – Dgen Vnk Jul 27 '18 at 12:44
  • @DgenVnk `dangerouslySetInnerHTML` is the React way of doing it, but you should only do it if you trust the HTML in the string and you absolutely have to. – Tholle Jul 27 '18 at 12:45
1

Here is your solution.

const obj = {
  article: '<p class="md-block-unstyled">First text...</p><p>Second text></p>'
} 


<div dangerouslySetInnerHTML={{__html: obj.article}} />
Amir
  • 11
  • 5