Pass class names as props to React components

avatar

Borislav Hadzhiev

Thu Apr 21 20222 min read

banner

Photo by Tina Rolf

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 classes' name, the classes would get applied perfectly fine.

Use the search field on my Home Page to filter through my more than 1,000 articles.