Sub topic 4
Attributes in JSX: className, style, and camelCase
This chapter assumes you know JavaScript objects, template literals, and basic HTML attributes. It also assumes you have read the earlier chapters on function components, JSX syntax, and curly-brace expressions. Here you will learn how JSX attributes differ from HTML attributes, and which mistakes come up most often.
Attributes are props on elements
JSX looks like HTML, but attributes in JSX become properties on a JavaScript object. For a built-in element such as <img>, React reads that object and sets the matching properties or attributes on the DOM node. This explains most of the differences from HTML:
- Names follow the DOM property names in camelCase, not the HTML attribute names.
- Values can be string literals or JavaScript expressions.
- Some attributes take objects or functions, not strings.
Here is a component that uses several kinds of attributes.
function Profile() {
const user = { name: 'Ada', imageUrl: 'https://example.com/ada.png' };
return (
<img
className="avatar"
src={user.imageUrl}
alt={user.name}
style={{ width: 64, height: 64 }}
/>
);
}Four attributes appear here, and each one shows a different rule.
className="avatar"is a string literal in quotes.src={user.imageUrl}is an expression in curly braces.alt={user.name}is also an expression. It reads a field from an object.style={{ width: 64, height: 64 }}takes an object, so it has two pairs of braces.
String literals versus expressions
An attribute value is either a quoted string or a braced expression. Use quotes when the value is fixed text. Use braces when the value is computed or is not a string.
function Link({ id }) {
return (
<a href={'/items/' + id} title="Open item" tabIndex={0}>
Open
</a>
);
}tabIndex={0} needs braces because 0 is a number. Writing tabIndex="0" would also work for this attribute, but it passes a string. For your own components, the difference matters. A prop written as count="3" is the string "3", while count={3} is the number 3.
Do not combine the two forms. href="/items/{id}" is not interpolation. It sends the literal text /items/{id}. If you need to build a string, use a braced expression with concatenation or a template literal.
function Link({ id }) {
return <a href={`/items/${id}`}>Open</a>;
}Why className and not class
In HTML you write class="avatar". In JSX you write className="avatar". JSX is JavaScript syntax, and React maps attribute names to DOM properties. The DOM property for the CSS class list is className, because class is a reserved word in JavaScript. React's own documentation uses className throughout.
The same reasoning explains htmlFor. The HTML for attribute on a <label> becomes htmlFor, because for is also a JavaScript keyword.
function EmailField() {
return (
<div className="field">
<label htmlFor="email">Email</label>
<input id="email" type="email" />
</div>
);
}The id and htmlFor values must match so that clicking the label focuses the input. If a component appears more than once on a page, a fixed id creates duplicates. The useId hook from React is the tool for that case, but it is outside this chapter.
Building class names dynamically
A common need is to add a class only when a condition holds. Use a template literal or a ternary.
function Badge({ label, active }) {
const className = active ? 'badge badge-active' : 'badge';
return <span className={className}>{label}</span>;
}Avoid this pattern:
<span className={`badge ${active && 'badge-active'}`}>When active is false, the string becomes badge false. When active is undefined, you get badge undefined. Use a ternary that returns an empty string instead.
function Badge({ label, active }) {
return (
<span className={`badge ${active ? 'badge-active' : ''}`}>{label}</span>
);
}This leaves a trailing space when active is false, which is harmless in CSS. Many projects use a small helper library such as clsx for longer lists of conditions, but plain JavaScript is enough for one or two.
camelCase attribute names
Most multi-word HTML attributes become camelCase in JSX. The table lists the ones you will meet most often.
| HTML | JSX |
|---|---|
| `class` | `className` |
| `for` | `htmlFor` |
| `tabindex` | `tabIndex` |
| `maxlength` | `maxLength` |
| `readonly` | `readOnly` |
| `autofocus` | `autoFocus` |
| `onclick` | `onClick` |
| `stroke-width` (SVG) | `strokeWidth` |
Two groups of attributes are exceptions to the camelCase rule.
aria-*attributes keep their hyphens, such asaria-labelandaria-hidden.data-*attributes keep their hyphens, such asdata-id.
function CloseButton({ onClose }) {
return (
<button type="button" aria-label="Close dialog" data-testid="close" onClick={onClose}>
×
</button>
);
}If you write an unknown or wrongly cased name on a built-in element, React usually prints a warning in the browser console, for example when you use class. Read these warnings. They point directly at the attribute that needs a different name.
Boolean attributes
For boolean attributes such as disabled, you can write the name alone or pass an expression.
function SubmitButton({ busy }) {
return <button type="submit" disabled={busy}>Save</button>;
}Writing <button disabled> is the same as disabled={true}. Passing false removes the attribute from the DOM. Passing the string "false" does not do that. For disabled, any string, including "false", counts as true in the DOM sense, so always pass a real boolean.
The style attribute takes an object
In HTML, style is a string of CSS declarations. In JSX, style takes a JavaScript object. That is why you see double braces: the outer pair marks a JavaScript expression, and the inner pair is the object literal.
function Box() {
return (
<div style={{ backgroundColor: 'tomato', marginTop: 8, padding: '4px 8px' }}>
Styled box
</div>
);
}The rules for the object are:
- Property names are camelCase:
backgroundColor, notbackground-color. - String values hold full CSS values, such as
'4px 8px'or'tomato'. - A plain number is treated as pixels for most properties.
marginTop: 8becomes8px. - Unitless properties such as
opacity,zIndex,flex, andlineHeightkeep a plain number as is.
function Faded() {
return <p style={{ opacity: 0.5, lineHeight: 1.5, fontSize: 18 }}>Faded text</p>;
}Here opacity and lineHeight stay unitless, while fontSize: 18 becomes 18px.
You can also define the object first, which keeps the markup readable.
const boxStyle = { backgroundColor: 'tomato', padding: 12 };
function Box() {
return <div style={boxStyle}>Styled box</div>;
}A string value such as style="color: red" causes an error in React, because React expects an object. This is one of the most common mistakes for people who move from HTML.
Limits of inline styles
Inline styles cannot express everything CSS can. They have no pseudo-classes such as :hover, no media queries, and no pseudo-elements. Use them for values that depend on data, such as a progress bar width, and put the rest in CSS classes.
function ProgressBar({ percent }) {
return (
<div className="progress">
<div className="progress-fill" style={{ width: `${percent}%` }} />
</div>
);
}Here the class carries the fixed appearance, and style carries the one value that changes.
Self-closing tags and attribute rules
Every JSX tag must be closed. Elements with no children, such as <img>, <input>, and <br>, need a slash: <img />. HTML lets you leave these open, but JSX does not.
Other rules about attributes:
- Attribute names are not repeated on the same element.
- The spread syntax
{...props}copies every field of an object onto the element as attributes. - When an attribute appears after a spread, it overrides the spread value.
function TextInput(props) {
return <input type="text" {...props} className="input" />;
}In this example, any className passed through props is replaced by "input". Moving className before the spread reverses that. Order matters, so decide which side should win.
Spreading is convenient, but it can forward attributes you did not intend to pass to the DOM. Prefer naming the props you need when a component has a small, fixed interface.
Attributes on your own components
Everything above applies to built-in elements. On a component you wrote, attribute names are only prop names, and React does not map them to the DOM. <Avatar className="big" /> passes a prop called className to Avatar. It has no effect unless Avatar reads that prop and applies it.
function Avatar({ src, className = '' }) {
return <img src={src} alt="" className={`avatar ${className}`} />;
}
export default function App() {
return <Avatar src="https://example.com/ada.png" className="big" />;
}Here Avatar accepts className and adds it to its own class. Passing style works the same way: forward it explicitly or it is ignored.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| `class="x"` | Console warning, class may not apply | Use `className` |
| `style="color: red"` | Error that style must be an object | Use `style={{ color: 'red' }}` |
| `background-color` in a style object | Syntax error in the object | Use `backgroundColor` |
| `href="/a/{id}"` | Literal braces in the URL | Use `` href={`/a/${id}`} `` |
| `<img>` without a slash | Compile error | Write `<img />` |
| Class passed to a custom component | Nothing changes | Read and apply the prop inside it |
How attribute handling fits together
Exercise
This component has three mistakes in its attributes. Name each one and write the corrected version. function Notice({ level }) { return ( <div class="notice" style="background-color: gold; padding: 8"> <label for="ack">Acknowledge</label> <input id="ack" type="checkbox"> </div> ); }
Show answer
The mistakes are: class should be className; style must be an object with camelCase names; for should be htmlFor; and <input> must be self-closed. Corrected:
function Notice({ level }) {
return (
<div className="notice" style={{ backgroundColor: 'gold', padding: 8 }}>
<label htmlFor="ack">Acknowledge</label>
<input id="ack" type="checkbox" />
</div>
);
}
Exercise
A Badge component receives active as a boolean and renders <span className={badge ${active && 'badge-active'}}>. What class string results when active is false, and how do you fix it?
Show answer
The result is badge false. Fix it with a ternary that yields an empty string: className={badge ${active ? 'badge-active' : ''}}.
Exercise
What does style={{ width: 40, opacity: 0.5 }} produce, and why does width get a unit while opacity does not?
Show answer
It sets width: 40px and opacity: 0.5. React appends px to plain numbers for most length-like properties, but unitless properties such as opacity, zIndex, flex, and lineHeight keep the number as written.