JSX Attributes

JSX attributes use camelCase, and className replaces class.

Syntax<img src={url} alt="logo" className="logo" />

JSX attributes look like HTML attributes but follow JavaScript naming. Because class and for are reserved words, React uses className and htmlFor instead.

Key differences from HTML

  • Use className instead of class.
  • Most attributes are camelCase: onClick, tabIndex, maxLength.
  • Pass non-string values in braces: disabled={true} or style={{ color: 'red' }}.

The style attribute takes a JavaScript object, not a string, and its keys are camelCased CSS properties.

Example

Example Β· javascript
function Avatar() {
  const url = 'https://example.com/ada.jpg';
  return (
    <img
      src={url}
      alt="Ada Lovelace"
      className="avatar"
      style={{ borderRadius: '50%', width: 64 }}
    />
  );
}

When to use it

  • A form-builder converts an HTML snippet to JSX, automatically renaming class to className and for to htmlFor so the generated code compiles without warnings.
  • An accessibility audit tool checks JSX attributes to ensure aria-label values are present and that htmlFor wires each label to the correct input id.
  • A component library documents that all style attributes must be passed as JavaScript objects, preventing developers from accidentally using CSS string syntax.

More examples

className and htmlFor

Shows the two most common JSX attribute renames: className instead of class, and htmlFor instead of for.

Example Β· jsx
function EmailField() {
  return (
    <div className="form-group">
      <label htmlFor="email">Email</label>
      <input
        id="email"
        type="email"
        className="input"
        autoComplete="email"
      />
    </div>
  );
}

Inline style as an object

Demonstrates passing the style attribute as a JavaScript object with camelCase property names, not a CSS string.

Example Β· jsx
function Highlight({ color, children }) {
  return (
    <span style={{ backgroundColor: color, padding: '2px 6px' }}>
      {children}
    </span>
  );
}

Spread props onto an element

Uses the spread operator to forward arbitrary attributes to the underlying DOM element, a common pattern in design systems.

Example Β· jsx
function Button({ className = '', ...rest }) {
  return (
    <button
      className={`btn ${className}`.trim()}
      {...rest}
    />
  );
}

// Usage
// <Button onClick={handleSave} disabled={isSaving}>Save</Button>

Discussion

  • Be the first to comment on this lesson.