1

I'm working on a project where I get back a string from the backend, that contains some html. I'd now like to put this html into gatsby:

let htmlFromBackend = `<b>Hello there</b>, partner!`

return (
  <div>
   {htmlFromBackend}
  </div>
)

However, this prints out the html as plain text, so what I see on the screen is literally:

<b> Hello there</b>, partner!

Whereas it should be

Hello there, partner!

How can I render this as proper html?

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
antonwilhelm
  • 5,768
  • 4
  • 19
  • 45

3 Answers3

2

You can use dangerouslySetInnerHTML however be sure you trust the data coming from the backend as you don't get any protection from XSS attacks.

let htmlFromBackend = `<b>Hello there</b>, partner!`

return (
  <div dangerouslySetInnerHTML={{ __html: htmlFromBackend }} />
)
Richard Scarrott
  • 6,638
  • 1
  • 35
  • 46
2

You can use useRef hook and set the element's innerHTML:

  const ref = useRef(null);

  useEffect(() => {
    let htmlFromBackend = `<b>Hello there</b>, partner!`;
    ref.current.innerHTML = htmlFromBackend;
  }, []);

  return <div ref={ref} />;
lissettdm
  • 12,267
  • 1
  • 18
  • 39
0

Install html-react-parser

npm i html-react-parser;

And in the component

import Parser from 'html-react-parser';

let htmlFromBackend = `<b>Hello there</b>, partner!`

return (
  <div>
   {Parser((htmlFromBackend)}
  </div>
)
RamiReddy P
  • 1,628
  • 1
  • 18
  • 29
  • thanks a lot. is there an advantage using `html-react-parser` over `dangerouslySetInnerHTML` (the other answer) ? – antonwilhelm Feb 06 '21 at 12:38
  • don't see any reason to use an additional package in your case, moreover it is a parser and not only dom parser, but react parser - a huge overkill imho. And `dangerouslySetInnerHTML` just puts your html inside a div, just as needed – crystalbit Feb 06 '21 at 13:16
  • 1
    I think you'd only want to use html-react-parser if you wanted to render custom components (e.g. instead of you want to render your own component with custom styles / state / behaviour). For just rendering plain HTML I would agree html-react-parser is overkill. – Richard Scarrott Feb 06 '21 at 13:19