0

I am building a web app for posting announcements. The user get to use a rich text editor, meaning he can make letters bold, underline them and so one. I am then saving this text with the description "content" in my mongodb database as a string. Every post has a title and a content. When i am displaying the post instead of showing "this text is strong" it is showing "< strong>this text is strong< /strong>". (added a space in < strong> cause it would make it strong otherwise. you get what i mean :P ) obviously this is not happening only in the strong case but with all the edits. for example in paragraphs its like this < p> paragraph < /p> and so on.

How can i display the content like its meant to be (styled) and not just as a string with no edits and style? Maybe it's the fact that i store it in my db as a string? but then what type should i store it as?

Posting images for reference

enter image description here

enter image description here

AVANISH RAJBHAR
  • 527
  • 3
  • 9
gevor
  • 79
  • 3
  • 13

1 Answers1

1

Allowing this is pretty dangerious, to be honest - you have to be EXTREMELY careful on what you allow and how you are sanitizing input (not allowing script tags, etc..)..

I wouldn't recommend doing this...

The reason this happens is because React is sanitizing the input for you (essentially turning any html into just a plain string - not true sanitization but you get the point)... if you want to render user input HTML, you have to use dangerouslySetInnerHTML - it must be presented in the following format: { __html: '<p>The Dangerous HTML</p>' }

const { useState, dangerouslySetInnerHTML } = React;
const { render } = ReactDOM;

function App() {
  const [html, setHtml] = useState();
  
  const handleChange = event => {
    setHtml({ __html: event.target.value});
  }
  
  return (
    <div>
      <h3>Enter some html</h3>
      <input onChange={handleChange} type="text" /> 
      {html && <div dangerouslySetInnerHTML={html} />}
    </div>
  );
}

render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
Matt Oestreich
  • 8,219
  • 3
  • 16
  • 41
  • yes i read about `dangerouslySetInnerHTML` and i was trying to avoid it. so there is no other way to display my text as edited without using this method? – gevor Feb 27 '20 at 14:29
  • 1
    Not that I'm aware of. If you do not use `dangerouslySetInnerHTML` then React will treat whatever you give it as just a regular string.. `dangerouslySetInnerHTML` is the only way to tell React that the string you want to render is actually HTML. The WYSIWYG editor you are using should be sanitizing input, though (like not allowing script tags, etc..) - and if it doesn't I'm sure you can find one out there that does. – Matt Oestreich Feb 27 '20 at 14:37