Home > Back-end >  Why does react not compile HTML present in a state
Why does react not compile HTML present in a state

Time:11-18

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 :- Edit frosty-tdd-ftchp

enter image description here

CodePudding user response:

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