classNames

Advertisement

NPM package classnames is most popular package which helps us to define the dynamic classes or we’ll add classes conditionally.

We are going to see how to use the NPM package classnames.

Table of contents:

Installation Installation

npm install classnames --save

OR

yarn add classnames

Top ↑

How to use classnames? How to use classnames?

We are going to see the usage of classnames with few examples.

Example with simple classes Example with simple classes

import { classNames } from 'classNames';

let cardClasses = classNames(
    'card',
    'card--black',
);

<div className={cardClasses}>
...
</div>

Here,
I have added the ‘card’ and ‘card–black’ classes to the “<div>”.
You may think why we need to use classNames() we can easily add the classes ‘card’ and ‘card–black’ to the div as:

<div className="card card--black">
..
</div>

Top ↑

Example with dynamic classes Example with dynamic classes

import { useState } from 'react';
import { classNames } from 'classNames';

let cardClasses = classNames(
    'card',
    'card--black',
    {
        'card--active': true,
    },
);

<div className={cardClasses}>
...
</div>
%d bloggers like this: