简体   繁体   中英

How to parse string in react to render html

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM