Course contentsShow
← React
Lesson 95 of 2,3963. JSX FundamentalsFree lesson

htmlFor Instead of for: Label Attribute Edge Case

Understanding why label's for attribute becomes htmlFor in JSX to avoid conflicts with JavaScript's for keyword.

htmlFor Instead of for: Label Attribute Edge Case

What you'll learn: Why React uses htmlFor instead of HTML's for attribute when linking labels to form inputs.

The JavaScript Keyword Conflict

In HTML, you connect a <label> to an <input> using the for attribute:

<!-- Standard HTML -->
<label for="username">Username:</label>
<input id="username" />

But there's a problem in JSX: for is a reserved keyword in JavaScript (used for loops). Just like class became className to avoid conflicts with JavaScript's class keyword, for becomes htmlFor in JSX.

The JSX Solution

When writing labels in React components, use htmlFor:

function LoginForm() {
  return (
    <div>
      <label htmlFor="username">Username:</label>
      <input id="username" type="text" />
    </div>
  );
}

Why This Matters

Remember that JSX compiles to JavaScript function calls. If React allowed for as a prop name, it would create syntax errors since for can't be used as an object property name without quotes in all contexts. By using htmlFor, React sidesteps this collision entirely.

When your JSX is rendered to the actual DOM, React automatically converts htmlFor back to the for attribute, so the browser behavior works exactly as expected—clicking the label still focuses the associated input.

Think of It Like This

It's similar to how you might rename a variable to avoid shadowing: if a word is "taken" by the language itself, you need an alternative that doesn't clash.

Key Takeaway: Use htmlFor instead of for when connecting labels to inputs in JSX, because for is a reserved JavaScript keyword and JSX must remain valid JavaScript syntax.