Why and how to use classnames utility in React components?
Solution 1
classnames
library lets you join different classes
based on different conditions in a simpler way.
Suppose you have 2 classes of which one is going to get used every time but the second one gets used based on some condition. So without classnames
library you would something like this
render() {
const classnames = 'firstClass';
if (someCondition) {
classnames += ' secondClass'
}
return(
<input className={classnames} .. />
);
}
But with classnames
library you would do that in this way
render() {
const classnames = {'firstClass', {'secondClass': someCondition}}
return(
<input className={classnames} .. />
);
}
Solution 2
In your case, <div className={classnames('search', className)}>
is equivalent to <div className={`search ${className}`}>
.
classnames
is mainly useful when you have to deal with conditional classes.
Solution 3
Classnames make it easy to apply class names to react component conditionally.
For example: Let create a state and apply a class to the button component when the button is clicked
const [isActive, setActive] = setState(false);
import classnames from "classnames"
var buttonClasses = classnames({
"btn": true,
"btn__active": isActive;
)}
<button className={buttonClasses} onClick={() => setActive(!isActive)}>Make me active</button>
This code will apply the "isActive" class to the button when it is clicked. I hope this help answer your question
Related videos on Youtube
John Taylor
Updated on June 22, 2022Comments
-
John Taylor almost 2 years
Could you please explain to me in a simple way what is the purpose of using Classnames utility in React code? I've just read Classnames docs, but I still can't grasp what is the main reason to use it in code like so:
import classnames from 'classnames'; [...] render() { const { className } = this.props return ( <div className={classnames('search', className)}> <div className="search-bar-wrapper"> <form className="search-form" onSubmit={this.onSearch.bind(this)}> <div className="search-bar"> <label className="screen-reader-only" htmlFor="header-search-form">Search</label> [...]
Full version of this code (jsx): https://jsfiddle.net/John_Taylor/j8d42m2f/2/
I don't understand what is going on this line of code:
<div className={classnames('search', className)}>
I've also read that ( how to use classnames library for React.js ) answer, but I still have problems with understanding my code snippet.
-
dawn over 4 yearsBeautifully explained.