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.

1
  • Please phrase your question correctly. What is the structure of your object ? Commented Jul 27, 2018 at 12:28

2 Answers 2

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>

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

2 Comments

Thanks you! But I would like to do it without using dangerouslySetInnerHTML. There is no other option to do it ?
@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.
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}} />

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.