Pass class names as props to React components

avatar

Borislav Hadzhiev

Last updated: Apr 21, 2022

banner

Photo from Unsplash

Pass class names as props to React components #

To pass class names as props to a React component:

  1. Pass a string containing the class names as a prop.
  2. Destructure the prop in the child component.
  3. Assign the class names to an element, e.g. <h2 className={className}>Content</h2>.
App.js
import './App.css'; function Child({className = ''}) { return ( <div> <h2 className={`text-big ${className}`}>Some content</h2> <h2 className={className}>More content</h2> </div> ); } export default function App() { return ( <div> <Child className="bg-lime" /> </div> ); }

The App.css file from the example might look something like:

App.css
.bg-lime { background-color: lime; } .text-big { padding: 2rem; font-size: 2rem; }

The example shows how to pass class names as props to a child component.

The className string we passed to the child can contain one or more space separated class names, just like you would pass them to an element.

If you need to combine existing class names with the passed in ones, use a template literal.

App.jsx
function Child({className = ''}) { return ( <div> <h2 className={`text-big ${className}`}>Some content</h2> <h2 className={className}>More content</h2> </div> ); }

We wrap the className prop in curly braces, so React knows that it has to evaluate an expression and pass in a template literal string to the className prop.

The dollar sign curly braces ${} syntax enables us to resolve an embedded expression.

The dollar sign curly braces syntax will get replaced with the value of the classNames variable.

If you aren't combining class names, you can just pass the provided from the parent class name as className={className}.

Notice that we passed an empty string as the default value for the className prop in the child component.

App.js
// 👇️ prop defaults to an empty string function Child({className = ''}) { return ( <div> <h2 className={`text-big ${className}`}>Some content</h2> <h2 className={className}>More content</h2> </div> ); }

If the parent component doesn't pass a className prop to the child, the prop's value would default to an empty string instead of undefined.

Even if we have a trailing space at the end of the class's name, the classes would get applied perfectly fine.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.