npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-dynamic-classnames

v0.0.21

Published

Separate styles and classes from your React components, seamlessly integrating with utility-first CSS libraries like UnoCSS and Tailwind. Like styled components for class names.

Downloads

413

Readme

react-dynamic-classnames

Separate styles and classes from your React components, seamlessly integrating with utility-first CSS libraries like UnoCSS and Tailwind. Like styled components for class names.

npm i react-dynamic-classnames --save-dev
# or
yarn add react-dynamic-classnames --dev

The "issue"

When working with utility-first libraries like uno.css or tailwind, it's common to define utility classes directly in your React components. While the below works for most of our cases, it can lead to cluttered and hard-to-maintain code, especially handling with conditional classes and/or dynamic styles. Often I do not want to create a wrapper component only to keep the styles separated.

const SomeButton = ({ isLoading, isActive, ...props } : SomeButtonProps) => {
  /* potentially logic here */

  const activeClass = useMemo(
    () => (isActive ? 'bg-blue-400 text-white' : 'bg-blue-400 text-blue-200'),
    [isActive],
  )
  const loadingClass = useMemo(() => (isLoading ? 'opacity-90 pointer-events-none' : ''), [isLoading])

  return (
    <button
      className={`text-lg mt-5 py-2 px-5 min-h-24 inline-flex transition-all z-10 ${someConfig.transitionDurationEaseClass} ${activeClass} ${loadingClass} ${props.className || ''}`}
      {...props}
    >
      {props.children}
    </button>
  )
}

What the tool does

It provides a alternative way to maintain classnames and styles for all valid React components. Just like styled components, but without the need for a additional library.

const SomeButton = dc.button<{ $isActive?: boolean; $isLoading?: boolean }>(
  ({ $isActive, $isLoading }) => `
    text-lg
    mt-5
    py-2
    px-5
    min-h-24
    inline-flex
    z-10
    transition-all
    ${someConfig.transitionDurationEaseClass}
    ${$isActive ? 'bg-blue-400 text-white' : 'bg-blue-400 text-blue-200'}
    ${$isLoading ? 'opacity-90 pointer-events-none' : ''}
  `,
)

Features

  • dynamic classnames
  • tiny, dev dependency
  • works with any utility-first CSS library (UnoCSS, Tailwind, etc.)
  • typscript
  • SSR-ready
  • CSS objects
  • nest components (experimental)

re-inventing the wheel?

There are other libraries that handle this area well, such as twin.macro and tailwind-styled-components. However, these solutions are either too complex for my projects, rely on styled-components, or lack SSR compatibility. I prefer a simpler approach with more separation of concerns for handling conditional classes, as demonstrated in the examples below.

Getting started

npm i react-dynamic-classnames --save-dev
# or
yarn add react-dynamic-classnames --dev

Basic usage

import { dc } from 'react-dynamic-classnames'

const Container = dc.div(`
  text-lg
  mt-5
  py-2
  px-5
  min-h-24
  inline-flex
  z-10
`);

Usage with props and css

// or extended pattern

interface ButtonProps {
  $isActive?: boolean
  $isLoading?: boolean
}

const SomeButton = dc.button<ButtonProps>(
  ({ $isActive, $isLoading }) => `
    text-lg
    mt-5
    py-2
    px-5
    min-h-24
    inline-flex
    z-10
    transition-all
    ${someConfig.transitionDurationEaseClass}
    ${$isActive ? 'bg-blue-400 text-white' : 'bg-blue-400 text-blue-200'}
    ${$isLoading ? 'opacity-90 pointer-events-none' : ''}
  `,
  // optional: css object with or without props
  ({ $isActive }) => ({
    boxShadow: `0 0 0 1px rgba(255, 255, 255, ${$isActive ? 0.7 : 0.2})`,
  }),
)

Usage with object pattern

The object pattern allows you to define dynamic classes and styles in a more readable way.

const Container = dc.button<ContainerProps>({
  // required: base class
  base: `
    text-lg
    mt-5
    py-2
    px-5
    min-h-24
    inline-flex
    z-10
    transition-all
    ${someConfig.transitionDurationEaseClass}
  `,
  // optional: dynamic classes
  classes: ({ $isActive, $isLoading }) => [
    $isActive ? 'bg-blue-400 text-white' : 'bg-blue-400 text-blue-200',
    $isLoading ? 'opacity-90 pointer-events-none' : '',
  ],
  // optional: css object with or without props
  css: ({ $isActive }) => ({
    boxShadow: `0 0 0 1px rgba(255, 255, 255, ${$isActive ? 0.7 : 0.2})`,
  }),
})

Prefix dynamic props with $

Note how we prefix the dynamic prop with a $ sign. This is a important convention to distinguish dynamic props from the ones we pass to the component.

This pattern should also avoid conflicts with reserved prop names.

Nest pre-styled components (Experimental)

To allow nesting of pre-styled components, we can use the restyle function. This function takes a pre-styled component and extends it with additional styles and classes.

Now we can define a base component and extend it with additional styles and classes and pass properties.

Currently untested with the extended pattern

import { dc, restyle, RestyleType } from 'react-dynamic-classnames'

// define a base component
const StyledSliderItemBase = dc.button<{ $active: boolean }>(
  ({ $active }) => `
    absolute
    h-full
    w-full
    left-0
    top-0
    ${$active ? 'animate-in fade-in' : 'animate-out fade-out'}
`,
)

// generate a type to infer the props
type StyledSliderItemBaseProps = RestyleType<typeof StyledSliderItemBase>

// we can now extend the base component
const NewStyledSliderItem = restyle<StyledSliderItemBaseProps>(
  StyledSliderItemBase,
  `
    rounded-small
    text-lg
  `,
)

// even with its own props
const NewStyledSliderItemWithProps = restyle<{ $secondBool: boolean } & StyledSliderItemBaseProps>(
  StyledSliderItemBase,
  ({ $active, $secondBool }) => `
    rounded-lg
    text-lg
    ${$active ? 'bg-blue' : 'bg-red'}
    ${$secondBool ? 'text-underline' : ''}
  `,
)

const SomeComponent = () => <>
  <StyledSliderItem $active />
  <NewStyledSliderItem $active />
  <NewStyledSliderItemWithProps $active $secondBool />
</>

Do I need react-dynamic-classnames?

No, in a perfect world, in smaller projects, everything is granular and well-organized, only 3-4 classnames per element, and we don't need this library.

Inspiration