DEV Community

Cover image for Passing className to components in React
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Passing className to components in React

In React, we are familiar with the concepts of a className on components. It's the way React adds the class attribute to an element.
It looks like this:

<div className="bg-red-200"></div>
Enter fullscreen mode Exit fullscreen mode

However, what happens if we want to make our custom components have the option to allow dynamic classNames?

To give you an example, let's say we have a CustomComponent that can take a className from wherever it's imported.

<CustomComponent className='bg-red-200` />
Enter fullscreen mode Exit fullscreen mode

If we ran this in React, we would get shown an error as the CustomComponent doesn't know what a className is.
So let's fix that.

Passing Classnames as props in React

In all honesty, I probably made it sounds like it was going to be very complicated, right?

Well, fear not, it's not that scary, as we can pass the className as a prop!

So in your child component, we would structure its receiving end like this.

export default Child = ({ className }) => {
  return (
    <div className={className}>
      <h2>I'm the child component</h2>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

And now, we can use this component like this.

<Child className='bg-red' />
Enter fullscreen mode Exit fullscreen mode

And that's it. Our component will now render this classname on its main div.

Mixing classes

I also wanted to take a second to look at what happens if your child component always has certain classes and you want to add extra classes.

In that case, the props stay the same. However, we can dynamically render them like this.

<div className={`existing-class ${className}`}>
Enter fullscreen mode Exit fullscreen mode

Our component will always render existing-class as a class but add whatever we set on it.

So if we use it like this:

<Child className='bg-red' />
Enter fullscreen mode Exit fullscreen mode

Our result will be a div like this.

<div class="existing-class bg-red"></div>
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (1)

Collapse
 
priyanshu3008 profile image
Priyanshu Ganatra

Thanks!