Sometimes, we want to add multiple classes to a React component.
In this article, we’ll look at how to add multiple classes to a React component.
Add Multiple Classes to a React Component
To add multiple classes to a React component, we can pass in an array of class name strings and join them together with a space.
For instance, we write:
import React from "react";
const isEnabled = true;
const isChecked = false;
export default function App() {
return (
<div
className={[isEnabled && "enabled", isChecked && "checked"]
.filter((e) => !!e)
.join(" ")}
>
hello world
</div>
);
}
We set the isEnabled to true and isChecked to false.
Then we set the className attribute to an array with isEnabled && "enabled" and isChecked && "checked" so that the strings are only added when the operand before the && is truthy.
Then we call filter with a callback to filter out the falsy values.
Finally, we call join with a space to join the class names together.
Therefore, the div should render with the enabled class only.
Conclusion
To add multiple classes to a React component, we can pass in an array of class name strings and join them together with a space.