Member-only story

Classnames: A small tool library that determines application class names based on conditions

Beck Moulton
2 min readJan 12, 2025

--

origin

When writing React components, we often struggle with setting class names for conditions.

import React, { useState } from 'react';export default function Button (props) {
const [isPressed, setIsPressed] = useState(false);
const [isHovered, setIsHovered] = useState(false); let btnClass = 'btn';
if (isPressed) btnClass += ' btn-pressed';
else if (isHovered) btnClass += ' btn-over'; return (
<button
className={btnClass}
onMouseDown={() => setIsPressed(true)}
onMouseUp={() => setIsPressed(false)}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
{props.label}
</button>
);
}

But with the help of the classnames tool library, it’s not that troublesome anymore.

import React, { useState } from 'react';
import classNames from 'classnames';export default function Button (props) {
const [isPressed, setIsPressed] = useState(false);
const [isHovered, setIsHovered] = useState(false); const btnClass = classNames({
btn: true,
'btn-pressed': isPressed,
'btn-over': !isPressed && isHovered,
}); // ...
}

Take the code above as an example.

Classnames will expose a utility function to the publicclassNames()When an object is passed in, its properties will be determined based on whether the property value istrue, added to the return…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

Responses (1)