JSX Special Attributes: className and htmlFor

In JSX, some familiar HTML attributes use different names because JSX follows JavaScript syntax and the DOM property model. The most common examples are `className` for HTML `class` and `htmlFor` for HTML `for`.

JSX is transformed into JavaScript, so attribute names must fit JavaScript and React's element-property conventions. As a result, the HTML `class` attribute is written as `className` in JSX.

For example, `Hello` assigns the element's CSS class. Writing `class="card"` is not the normal JSX form and can trigger a warning or incorrect behavior depending on the environment and tooling.

The HTML `for` attribute, commonly used with ``, is written as `htmlFor` in JSX: `Email`. This corresponds to the DOM `htmlFor` property and avoids using JavaScript's `for` keyword as an attribute identifier.

These names are specific to JSX syntax rather than replacements that should be used in ordinary HTML. When writing JSX, think in terms of the JavaScript-facing property names expected by the JSX/DOM implementation.

Key points

Interview questions

Why does JSX use `className` instead of `class`?

JSX is embedded in JavaScript, so it does not use every HTML attribute name literally. `className` is the JSX form used to assign an element's CSS class. It corresponds to the DOM-facing property name used for the element's class value. In ordinary HTML, the attribute remains `class`.

What is `htmlFor` in JSX, and why is it needed?

`htmlFor` is the JSX form of the HTML `for` attribute used by labels. It corresponds to the DOM `HTMLLabelElement.htmlFor` property and avoids using `for` as the JSX attribute identifier. For example, `htmlFor="email"` associates a label with an input whose `id` is `email`.

Are `className` and `htmlFor` special React features or general HTML rules?

They are JSX conventions rather than changes to the HTML specification. JSX uses JavaScript-oriented names when representing elements and their properties. React is a common consumer of JSX, but the JSX syntax itself is not synonymous with HTML. If you write literal HTML, you use `class` and `for` instead.

How would you correctly connect a label to an input in JSX?

Give the form control a unique `id` and set the label's `htmlFor` to the same value. For example, `Email` paired with `<input id="email" />` creates the explicit association. This lets the label target that control when the user interacts with the label. In reusable components, the ID should also be handled carefully so multiple instances do not accidentally share the same identifier.