8

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.

6 Answers 6

9

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} .. />
  );
}
0
1

In your case, <div className={classnames('search', className)}>is equivalent to <div className={`search ${className}`}>.

classnamesis mainly useful when you have to deal with conditional classes.

1

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

0

If used the way you use it in your script classnames simply joins the strings you give it with spaces.

const className = 'x';
const result = classnames('search', className);
// result == 'search x'
0

I think you should attempt reading the docs one more time, they are very clear. Specifically, this part:

So where you may have the following code to generate a className prop for a in React:

var Button = React.createClass({
  // ...
  render () {
    var btnClass = 'btn';
    if (this.state.isPressed) btnClass += ' btn-pressed';
    else if (this.state.isHovered) btnClass += ' btn-over';
    return <button className={btnClass}>{this.props.label}</button>;
  }
});

You can express the conditional classes more simply as an object:

var classNames = require('classnames');

var Button = React.createClass({
  // ...
  render () {
    var btnClass = classNames({
      btn: true,
      'btn-pressed': this.state.isPressed,
      'btn-over': !this.state.isPressed && this.state.isHovered
    });
    return <button className={btnClass}>{this.props.label}</button>;
  }
});

The sole purpose of the library here is to remove the need of writing ugly code to dynamically add classes to something, and just use a consistent syntax instead.

Another example:

var Button = React.createClass({
  render () {
    return <button className={this.props.foo ? 'bar' : 'baz' + this.props.bar ? 'baz' : 'foo'}>{this.props.label}</button>;
  }
});

That is really hard to read. There is a lot of code out there that looks similar to that.

Here is a better way, using classnames:

var classes = classNames({
    bar: this.props.foo,
    baz: !this.props.foo,
    active: this.props.bar,
    hover: !this.props.bar
});

var Button = React.createClass({
  render () {
    return <button className={classes}>{this.props.label}</button>;
  }
});

It's very clear there what's happening. If the values in the object are true, the key will be appended to the class. So in that example, the final class will be bar active, given this.props.foo is truthy and this.props.bar is truthy.

0

Your code snippet

<div className={classnames('search', className)}>

is equivalent to:

<div className={`search ${className ? className : ""}`}>

so in this particular case it's just encapsulates ternary operator from inside template string. Which is small but improvement - harder to produce bug in.

Probably it is simplest case of using classnames, however when you'll have more and more conditions around your class name manipulations, it is going to be more and more useful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.