Why className, not class?
Short answer
JSX uses className instead of class,
because class is a reserved word in JavaScript,
and JSX is not HTML but JavaScript syntax that just looks like HTML.
Detailed explanation
Under the hood, JSX turns into ordinary JavaScript code. For example:
<div className="button">Button</div>turns into:
React.createElement("div", { className: "button" }, "Button");If you had written:
<div class="button">Button</div>then during compilation this would look like:
React.createElement("div", { class: "button" }, "Button");But in JavaScript you cannot use class as a property name in a plain object without quotes,
because class is a keyword for declaring classes:
class Button {}So React (and Babel) deliberately replace class with className,
so there are no syntax conflicts and the code stays valid JS.
Why className specifically
Because in the browser's DOM API, the property for CSS classes is also called className.
An example from plain JavaScript:
const el = document.createElement("div");
el.className = "button"; // correct
console.log(el.className); // "button"If you try:
el.class = "button"; // error: no such propertySo React follows the same rules as the DOM, so behavior is predictable and familiar.
Example
Correct:
<div className="card active">Content</div>Error:
<div class="card active">Content</div>
// JSX error: Unexpected token 'class'Summary
| In HTML | In JSX | Why |
|---|---|---|
class | className | class is reserved in JS |
for | htmlFor | for is reserved in JS (used in loops) |
In one line
JSX is JavaScript, not HTML. That is why
classNameis used instead ofclass, to avoid a conflict with theclasskeyword.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.