EthicsComputerCourses
Join training +91 90532 10052

HTML Integration with React

HTML · Lesson 189 of 234 Advanced 11 min read Updated

By the end of this lesson you will be able to predict the HTML that React renders from your JSX, use fragments, keys and useId to keep that HTML valid and accessible, put page metadata in components, and spot the HTML mistakes that React lets through.

What you should know first: HTML in Templates & Frameworks (the JSX attribute table, hydration errors and escaping), Accessible Form Error Handling and Safe DOM Manipulation. This lesson does not teach React. For components, props and state, use the React tutorial. The version checked is React 19.3 (react-dom 19.3.1), and every output block below was produced by running that version with Node.js.

From JSX to HTML

You already know that JSX writes className, htmlFor, camelCase attributes and closed tags. The browser never sees JSX. ReactDOM is the part of React that turns your components into real DOM elements in the browser, or into an HTML string on the server.

Think of a railway reservation form. You write "Jaipur Exp, 2 adults", and the clerk prints a ticket with exact train and berth codes. JSX is the form; the HTML is the ticket. To check a journey you read the ticket, so learn to read React's output.

This component uses several JSX rules at once:

React JSX
import { useId, useState } from "react";

function PinField() {
  const id = useId();
  const [pin, setPin] = useState("302001");
  return (
    <>
      <label htmlFor={id}>PIN code</label>
      <input
        id={id}
        className="field"
        inputMode="numeric"
        maxLength={6}
        aria-describedby={id + "-hint"}
        value={pin}
        onChange={(e) => setPin(e.target.value)}
        style={{ fontSize: 16, marginTop: "4px" }}
      />
      <p id={id + "-hint"}>6 digits, for example 302001.</p>
    </>
  );
}

Rendered on the server with renderToString from react-dom/server, it becomes:

Output
<label for="_R_0_">PIN code</label><input id="_R_0_" class="field" inputMode="numeric" maxLength="6" aria-describedby="_R_0_-hint" style="font-size:16px;margin-top:4px" value="302001"/><p id="_R_0_-hint">6 digits, for example 302001.</p>

Read it like a ticket:

  • className and htmlFor became class and for.
  • inputMode, maxLength and readOnly keep their capital letters in the string. That is fine, because HTML attribute names are not case-sensitive.
  • The style object became a CSS string. Numbers got px (16 became 16px), except for unitless properties such as lineHeight and zIndex.
  • onChange is gone. Event handlers never appear in the HTML; React attaches them with JavaScript.
  • The fragment <>...</> left no element behind.
  • useId produced _R_0_. In the browser it produces a lowercase form such as _r_0_.

A few more rules from the same test run: disabled={false} removes the attribute completely, hidden={true} becomes hidden="", and aria-hidden={false} becomes aria-hidden="false", because ARIA attributes are strings. When text and values sit side by side, as in Hello, {name}!, the server inserts empty comments (<!-- -->) between them so the browser can tell the text pieces apart during hydration.

Fragments instead of div soup

Div soup is a page made of nested <div> elements that exist only because a component needed a single parent. It hides the structure from screen readers, and in some places it breaks HTML rules.

A table row is the classic case. This component wraps its cells in a <div>:

React JSX
function Cells() {
  return <div><td>Pune</td><td>₹450</td></div>;
}

Used inside a <tr>, it makes React's development build print this warning in the browser console:

Output
In HTML, <div> cannot be a child of <tr>.
This will cause a hydration error.

Return a fragment, <><td>Pune</td><td>₹450</td></>, and the cells sit directly in the row. When you map a list into pairs of elements, such as a <dt> and a <dd> in a description list, you need a fragment that takes a key. Use the long form, Fragment:

React JSX
import { Fragment } from "react";

<dl>
  {timings.map((t) => (
    <Fragment key={t.id}>
      <dt>{t.day}</dt>
      <dd>{t.hours}</dd>
    </Fragment>
  ))}
</dl>
Output
<dl><dt>Monday</dt><dd>9 am to 6 pm</dd><dt>Sunday</dt><dd>Closed</dd></dl>

Lists and keys

A key tells React which item is which when a list changes. It is not an HTML attribute: the output of items.map((c) => <li key={c.id}>{c.name}</li>) is just <ul><li>HTML</li><li>CSS</li></ul>. Leave the key out and the development build warns: Each child in a list should have a unique "key" prop.

Use a stable value from your data, such as an order number. Using the array index as the key breaks as soon as items are reordered or removed: React reuses the wrong element, so a typed value or the focus can jump to a different row. The details are in Lists & Keys.

Controlled forms with real labels

A controlled input is one whose value comes from React state and changes only through onChange. Two HTML rules still apply in full.

First, every input needs a label connected with htmlFor and id. Placeholders do not replace labels. Second, ids must be unique in the whole page. A component that hard-codes id="pin" works once and breaks the second time it is used. That is what useId is for: it gives each component instance its own id, the same on the server and in the browser. Build related ids from it, such as id + "-hint" and id + "-error", and never hard-code or parse its format, because it has changed between React versions.

If you give an input a value but no onChange, React warns that it will be a read-only field and suggests defaultValue, onChange or readOnly. React's own forms lesson, Forms & Controlled Inputs, shows both styles.

The example below is the real React output of two components, each used twice: one with useId, one with a fixed id. The script asks the browser what it actually connected.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>React output: labels and ids</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    form { border: 1px solid #999; padding: 8px 12px; margin-bottom: 12px; }
    label, input { display: block; }
    pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
  </style>
</head>
<body>
  <h1>Two delivery PIN fields</h1>

  <h2>With useId (React output)</h2>
  <form id="good"><label for="_R_1_">Home PIN code</label><input id="_R_1_" inputMode="numeric" maxLength="6" aria-describedby="_R_1_-hint" value=""/><p id="_R_1_-hint">6 digits, for example 302001.</p><label for="_R_2_">Office PIN code</label><input id="_R_2_" inputMode="numeric" maxLength="6" aria-describedby="_R_2_-hint" value=""/><p id="_R_2_-hint">6 digits, for example 302001.</p></form>

  <h2>With id="pin" hard-coded (React output)</h2>
  <form id="bad"><label for="pin">Home PIN code</label><input id="pin" inputMode="numeric" maxLength="6" value=""/><label for="pin">Office PIN code</label><input id="pin" inputMode="numeric" maxLength="6" value=""/></form>

  <pre id="out"></pre>

  <script>
    const lines = [];
    for (const form of document.forms) {
      lines.push("Form #" + form.id);
      form.querySelectorAll("input").forEach((input, i) => {
        const names = [...input.labels].map((l) => l.textContent).join(" + ") || "(no label)";
        lines.push("  input " + (i + 1) + ": label = " + names +
          ", inputMode = " + input.inputMode + ", maxLength = " + input.maxLength);
      });
    }
    lines.push("Elements with id=pin: " + document.querySelectorAll("#pin").length);
    document.querySelector("#out").textContent = lines.join("\n");
  </script>
</body>
</html>

The report shows that the useId version connects "Home PIN code" and "Office PIN code" to their own inputs. In the hard-coded version, the first input gets both labels and the second gets none, because for="pin" always finds the first element with that id. Clicking "Office PIN code" focuses the wrong box. Notice also that inputMode and maxLength work, even with capital letters in the markup.

Landmarks and page structure

React will happily render a page of <div> elements with click handlers, and the HTML then has no landmarks, headings or buttons. Return the real elements instead: a layout component with <header>, <nav>, one <main> and <footer>, <h1> to <h6> in order, <a href> for navigation and <button> for actions.

Below is React's output for the same small shop page written two ways. The script lists what a screen reader's landmarks and headings menus, and the keyboard, would find.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>React output: div soup vs semantic</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    table { border-collapse: collapse; }
    th, td { border: 1px solid #999; padding: 4px 8px; text-align: left; }
  </style>
</head>
<body>
  <h1>What assistive technology finds</h1>

  <template id="soup"><div class="app"><div class="top"><div class="logo">Kochi Books</div><div class="links"><div>Home</div><div>Offers</div></div></div><div class="content"><div class="title">New arrivals</div><div class="btn">Add to cart</div></div></div></template>

  <template id="semantic"><header><a href="/" class="logo">Kochi Books</a><nav aria-label="Main"><ul><li><a href="/">Home</a></li><li><a href="/offers">Offers</a></li></ul></nav></header><main><h1>New arrivals</h1><button type="button">Add to cart</button></main><footer><p>Kochi Books, MG Road</p></footer></template>

  <table>
    <thead><tr><th>Version</th><th>Landmarks</th><th>Headings</th><th>Keyboard stops</th></tr></thead>
    <tbody id="rows"></tbody>
  </table>

  <script>
    for (const id of ["soup", "semantic"]) {
      const page = document.getElementById(id).content;
      const landmarks = [...page.querySelectorAll("header, nav, main, footer")].map((el) => el.localName);
      const headings = [...page.querySelectorAll("h1, h2, h3")].map((h) => h.textContent);
      const stops = [...page.querySelectorAll("a[href], button")].map((el) => el.textContent);
      const tr = document.createElement("tr");
      for (const text of [id, landmarks.join(", "), headings.join(", "), stops.join(", ")]) {
        const td = document.createElement("td");
        td.textContent = text || "none";
        tr.append(td);
      }
      document.querySelector("#rows").append(tr);
    }
  </script>
</body>
</html>

The div soup row reads "none" in every column, although the React version had onClick on three <div> elements. The semantic row lists four landmarks, the heading "New arrivals" and four keyboard stops. Same design, a completely different page for a screen reader. Focus management after route changes is covered in Accessibility in React.

Title and meta tags in components

Since React 19, a component can render <title>, <meta> and <link> anywhere in its tree, and ReactDOM moves them into <head>. In our test, rendering a whole document on the server placed them in <head>, and in the browser createRoot added them to document.head and document.title changed.

React JSX
function OrdersPage({ shop }) {
  return (
    <>
      <title>{`Orders | ${shop}`}</title>
      <meta name="description" content="Your recent orders" />
      <main><h1>Your orders</h1></main>
    </>
  );
}

Notice the template literal. <title>Orders | {shop}</title> has two children, the text and the value, and React needs a single string. React's development build warns, and in our server test the result was an empty <title></title>. Two more cautions: if your index.html already has a <title>, the page now has two, so remove the static one or treat it only as a fallback. And frameworks such as Next.js have their own metadata system; see HTML Integration with Next.js.

dangerouslySetInnerHTML

React escapes every value you put in { }. In our test, the text <b>Hi</b> & bye came out as &lt;b&gt;Hi&lt;/b&gt; &amp; bye. React 19 also blocks javascript: URLs in href: it replaced one with a URL that throws an error instead of running code.

dangerouslySetInnerHTML={{ __html: html }} switches that off. The string is inserted as given, like innerHTML, so a review containing <img src=x onerror=...> runs its script for every visitor. Use it only for HTML you control or have sanitised with a library such as DOMPurify, never mix it with children, and prefer rendering the data as elements. HTML Injection & DOM-Based XSS and Security in React Apps go deeper.

Common mistakes

  • Wrapping elements in <div> to satisfy JSX. Use a fragment, especially inside <tr>, <ul>, <dl> and <select>.
  • Index as key in editable lists. Typed values and focus jump between rows.
  • Hard-coded ids in reusable components. Use useId and build related ids from it.
  • <div onClick> as a button. The HTML output has no role and no keyboard stop.
  • <title>Text {value}</title>. Pass one string, such as a template literal.
  • dangerouslySetInnerHTML on user content. Sanitise first, or render elements.

Interview questions

1. Does the key prop appear in the rendered HTML?

No. key is used only by React to match list items between renders. The output of a mapped list is plain <li> elements. Keys must be stable and unique among siblings, which is why database ids are better than array indexes.

2. Why use useId instead of a fixed id in a form component?

Ids must be unique in the page. A fixed id breaks as soon as the component is rendered twice, because for and aria-describedby then point to the first matching element. useId gives each instance a unique id that also matches between server and client rendering.

3. When do you need <Fragment key> instead of <>?

When you map a list into groups of sibling elements, such as a <dt> and <dd> pair, each group needs a key, and the short <> syntax cannot take one. Fragment with a key groups them without adding a wrapper element that would break the <dl>.

4. What does React 19 do with a <title> rendered inside a component?

ReactDOM places it in the document <head>, on the server when it renders a full document and in the browser through document.head, so each page component can set its own title and meta tags. The title's children must form a single string.

5. Why is dangerouslySetInnerHTML dangerous?

It bypasses React's escaping and inserts the string as raw HTML. If any part comes from users, they can inject elements with event handlers that run script in other visitors' browsers. Sanitise it or render the content as React elements.

Key points

  • Read React's output, not the JSX: class, for, CSS strings with px, no handlers, no keys.
  • Fragments avoid wrapper <div> elements that break tables, lists and description lists.
  • Keys stay inside React; use stable ids from your data, not array indexes.
  • Connect every controlled input to a <label>, and use useId for ids in reusable components.
  • Render real landmarks, headings, links and buttons; React will render <div> soup without complaint.
  • React 19 hoists <title> and <meta> into <head>; give <title> a single string.
  • dangerouslySetInnerHTML bypasses escaping; only use it with trusted or sanitised HTML.

Exercise

Aarav wrote this component for a Lucknow coaching centre and uses it three times on one page: function Batch({ name, seats }) { return <div><label for="seats">Seats for {name}</label><input id="seats" value={seats} /><div onClick={book}>Book</div></div>; }. List every HTML and accessibility problem in its output, then rewrite it with useId, a controlled input, a real button and no wrapper <div>.

Show solution
React JSX
import { useId, useState } from "react";

function Batch({ name, initialSeats, onBook }) {
  const id = useId();
  const [seats, setSeats] = useState(initialSeats);
  return (
    <>
      <label htmlFor={id}>{`Seats for ${name}`}</label>
      <input
        id={id}
        type="number"
        min={1}
        max={10}
        value={seats}
        onChange={(e) => setSeats(e.target.value)}
      />
      <button type="button" onClick={() => onBook(name, seats)}>
        {`Book ${name}`}
      </button>
    </>
  );
}

The original used for (React warns and expects htmlFor), repeated id="seats" three times so every label pointed at the first input, set value without onChange so the field was read-only, and rendered "Book" as a <div> with no role or keyboard access. The rewrite uses useId, controlled state, a real <button> whose text names the batch, and a fragment instead of the wrapper.

Quick Quiz

1. What does ReactDOM render for style={{ fontSize: 16 }}?

2. A reusable field component hard-codes id="email" and is rendered twice. What happens?

3. Which JSX gives a correct <title> in React 19?

4. Which rendered output shows a key from <li key={c.id}>?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call