Issue
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?
Solution
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;
Answered By - DCodeMania
Answer Checked By - - Marilyn (ReactFix Volunteer)