Borislav Hadzhiev
Thu Apr 21 2022·2 min read
Photo by Tina Rolf
To pass class names as props to a React component:
<h2 className={className}>Content</h2>
.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:
.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.
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.
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.
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.
// 👇️ 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.