36

I am using ReactJS do develop a simple chat application. Could someone help me to sanitize the input . There is only one input text box to send chat messages. How to sanitize it?.

<input type="text"
              className="chat"
              value={this.state.name}
            />

Based on the documentations HTML escapes html by default. Is it enough?. Do I need to add any other sanitization methods. If yes, please let me know how to do that?.

Shamnad P S
  • 1,095
  • 2
  • 15
  • 43

2 Answers2

53

It's sanitized by default, you don't need a sanitization method unless you are using dangerouslySetInnerHTML which is not the case.

Nevus
  • 1,307
  • 1
  • 9
  • 21
dgrijuela
  • 683
  • 7
  • 9
  • 1
    Are there any documentation on this?. – Shamnad P S Apr 24 '17 at 10:30
  • 20
    https://facebook.github.io/react/docs/introducing-jsx.html#jsx-prevents-injection-attacks "By default, React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that's not explicitly written in your application. Everything is converted to a string before being rendered. This helps prevent XSS (cross-site-scripting) attacks." – dgrijuela Apr 24 '17 at 13:01
  • @SunnyPatel that would be outside the React DOM so it would need to be sanitized. But do that directly in the backend, never trust what comes from the frontend – dgrijuela Aug 19 '22 at 10:32
4

JSX expressions {} automatically take care of encoding HTML before rendering, which means even if u don't sanitise your input your webpage is XSS safe.

Please refer to this DOC in react site: jsx-prevents-injection-attacks

Note: If you want your user to allow typing in HTML.. then you need input Sanitisation and you have to use dangerouslySetInnerHTML as @dgrijuela mentioned in the above post.

  • 1
    JSX is just a grammar extension to javascript. There is nothing about the JSX spec which mandates sanitization. – brainkim Nov 02 '19 at 12:25
  • From your link: "By default, React DOM escapes any values embedded in JSX before rendering them". I read this to mean react is escaping the values, NOT JSX. – Terrabits Oct 18 '22 at 19:07