React Reference ยท Props and Attributes
React className prop
Reference for the className prop in React: add CSS classes in JSX, build class names conditionally, and avoid the false and array pitfalls.
className sets the CSS class of a DOM element. It is the JSX name for the HTML class attribute: class is a reserved word in JavaScript, and React's DOM properties mirror the names of the DOM (element.className) rather than the HTML attribute names. The value is a plain string of space-separated class names.
<button className="btn btn-primary">Save</button>
className accepts only a string (or undefined and null, which leave the attribute out). Anything else you pass is converted with String(), which is why arrays and false cause trouble. Build the string first, then pass it.
Try it
Syntax
<element className={string | undefined | null} />
| Name | Description |
|---|---|
className |
A string of class names separated by spaces. undefined and null omit the attribute. '' renders an empty class="". |
Returns: the element with a class attribute.
Errors and warnings: passing class instead of className still renders the attribute in React 19 but logs Invalid DOM property class. Did you mean className?. Passing false renders nothing and logs a warning about a non-boolean attribute. An array is converted to a comma-joined string ("a,b"), which is almost never intended. true is also rejected with a warning.
Usage notes
- Build with
filter(Boolean).join(' ')or a small helper such asclsx(a package not available in the TryIt sandbox) to combine conditional classes. Template literals work too, but leave strayundefinedorfalsetext in the string if you are not careful. - Do not interpolate user input into class names without checking it against an allow-list. A class is only styling, but a surprising class name can still match global CSS.
classNameis notclasson every kind of element. On SVG, React also usesclassNameand renders aclassattribute. On a custom element it becomesclassunless the element defines its ownclassNameproperty.- Do not edit
classListby hand on an element React renders. Change the state that producesclassNameinstead. React rewrites the whole attribute whenever the prop value changes, which discards classes you added manually. - CSS Modules and utility classes (Tailwind, for example) are just strings. With CSS Modules you pass
styles.card, an import that resolves to a generated class name. - Passing through. To let callers extend your component's style, accept a
classNameprop and merge it, as in the second example, instead of replacing your own classes. - Prop name conflicts. Components can name their own props anything, but pick
classNamefor "classes applied to the root element" so the convention carries over. - Dynamic styles that change often (a drag position, a progress width) belong in
styleor CSS variables, not in generated class names.
Related
style,htmlFor, data-* attributes, SVG elements- Lessons: Styling, JSX in depth