Home > Software design >  React hooks: setState() with string that contains html?
React hooks: setState() with string that contains html?

Time:02-11

I'm trying to setState from a json file value that contains html. So something like:

...
const quote = [quote, setQuote] = useState('');

const quotes = [
    { quote: "Some text." },
    { quote: 'Some text with <span >HTML</span>.' },
  ];
  const handleClick = () => {
    setQuote(quotes[1].quote);
  };
...
return (
  <div>{quote}</div> // right now it's printing the html as text.
);

CodePudding user response:

Use dangeriouslySetInnerHTML to parse and render an HTML string. You may also want to cleanse/sanitize any values with DOMPurify.

Example:

import DOMPurify from "dompurify";

...

const quote = [quote, setQuote] = useState('');

const quotes = [
  { quote: "Some text." },
  { quote: 'Some text with <span >HTML</span>.' },
];
const handleClick = () => {
  setQuote(quotes[1].quote);
};

...

return (
  <div dangerouslySetInnerHTML ={{ __html: DOMPurify.sanitize(quote) }} />
);

CodePudding user response:

Insert raw HTML using dangerouslySetInnerHTML:

return (
  <div dangerouslySetInnerHTML={{__html: quote }}></div>
);

CodePudding user response:

Injecting html from text is always a risk, but I think this should work:

import { useRef } from 'react';

...
const quoteRef = useRef(null);

const quotes = [
    { quote: "Some text." },
    { quote: 'Some text with <span >HTML</span>.' },
  ];
  const handleClick = () => {
    if(!quoteRef.current) return; //Just in case the element got deleted
    quoteRef.current.innerHTML = quotes[1].quote;
  };
...
return (
  <div ref={quoteRef}>{quote}</div> // right now it's printing the html as text.
);
  • Related