Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does react not compile HTML present in a state

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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>);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading