0

I'm working on a large React project where we are receiving data from an API we don't control Occasionally we need to receive an HTML string with inline styles and insert all of it directly in our component. It will be passed to us as a string -- I've not gotten a clear answer from the backend team, but I think it will be something like

<textarea rows='1' cols'50' >Some text with <span class='special style'>special styles applied</span></textarea>

How do I insert this into my react component correctly (and safely)? Simply something like the following?

const myHTMLStringFromAPI = getApiStuff()

  render(){
  return <div>{myHTMLStringFromAPI}</div>
}
Cerulean
  • 5,543
  • 9
  • 59
  • 111
  • 2
    Possible duplicate: https://stackoverflow.com/questions/23616226/insert-html-with-react-variable-statements-jsx – Eran Machiels Feb 18 '19 at 13:33
  • Possible duplicate of [Insert HTML with React Variable Statements (JSX)](https://stackoverflow.com/questions/23616226/insert-html-with-react-variable-statements-jsx) – Taki Feb 18 '19 at 13:36
  • It seems it is a duplicate. Should I just close the question? – Cerulean Feb 18 '19 at 13:37

1 Answers1

1

You can do what using dangerouslySetInnerHTML

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. This is used because setting innerHTML directly is risky.

const myHTMLStringFromAPI = getApiStuff()
  render(){
  return <div dangerouslySetInnerHTML={{__html:`<textarea rows='1' cols'50' >Some text with <span class='special style'>special styles applied</span></textarea>`}}>{myHTMLStringFromAPI}</div>
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73