Why does react not compile HTML present in a state

Viewed 62

I set a default value of a state to be <b> Hey </b> . Now when I rendered this state on the UI it printed the string instead of Hey wrote in bold.I want to know why it is not working. Why react is not able to interpret the html tag and show the appropriate output

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [html, setHtml] = useState("<b>Hey</b>");
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <div>{html}</div>
    </div>
  );
}

Output :-

enter image description here

Was expecting the output to be Hey written in bold.

Here's the codesandbox link for better understanding :- https://codesandbox.io/s/heuristic-chaum-vo6qt?file=/src/App.js

Thank you. I just want to know why react is not able to render the HTML tag as HTML tag instead of printing it out.

3 Answers

Because you are rendering a string, not HTML. If you want to render stringified HTML then use dangerouslySetInnerHTML, use caution what you pass through, in other words, you may want to run the string through a DOM purifier first.

export default function App() {
  const [html, setHtml] = useState("<b>Hey</b>");
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <div dangerouslySetInnerHTML={{ __html: html}} />
    </div>
  );
}

Edit frosty-tdd-ftchp

enter image description here

You are setting the value of html as "<b>Hey</b>" which is a string string that's why it renders that as it is. You can directly assign html to the variable like so:

  const [html, setHtml] = useState(<b>Hey</b>);

It's a string and not HTML, to fix that maybe you can insert it in the div as innerHTML ie.

document.querySelector(".divClassName").innerHTML = html
Related