0

I am building a very basic blog type app with a MERN stack and have it to the point where I can have a very simple post of just text. Can anyone suggest how I could parse that string to also render HTML in my content?

So a post would look like

Bold Text with a link

instead of

<b> Bold Text with <a href="#"> a link</a></b>

One idea I had was to try and use DOMParser in the component, something like

  const parser = new DOMParser();
  const parsedContent = parser.parseFromString(post.description, 'text/html');

// and then in the render just print it out
<div className='content'>
{parsedContent} 
</div>

That of course did not work because that is returning an entire html object and React errors with Objects are not valid as a React child.. if you meant to render a collection of children, use an array instead.

What would be the proper way to parse that string and render the HTML in my content?

0

1 Answer 1

1

You can just try this way:

const Test = () => {
    const text = '<b> Bold  Text with <a href="#"> a link</a></b>';

    return <div dangerouslySetInnerHTML={{ __html: text }} />;
};

export default Test;

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

1 Comment

Thank you, that works! I am not too worried about security for this one so willing to live dangerously ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.