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

utility-class-components

v0.2.5

Published

Build React components using utility classes in the styled-components way!

Downloads

183

Readme

import { utld, ud } from "utility-class-components";

const boxStyle = ud`
  w-32
  h-32

  bg-red-200
`;

const Container = utld.div<{ $isRed: boolean }>`
  flex
  text-bold

  ${boxStyle}

  ${({ $isRed }) => $isRed && "text-red-500"}
`;

function Page() {
  return <Container $isRed={true}>AWESOME!!</Container>;
}

Table Of Contents


Installation

This package is published on npm registry.

npm i utility-class-components
# or yarn add utility-class-components

Setting up

Setting up Tailwind CSS IntelliSense for utility-class-components

If you have installed the "Tailwind CSS IntelliSense" extenstion in VSCode, you can enable autocompletion inside utld and ud.

Add the following to your settings.json:

{
  "tailwindCSS.experimental.classRegex": [
    "utld(?:\\.[a-z0-9]*|\\([^)]*\\))(?:<[^>]*>|)`([^`]*)`",
    "ud`([^`]*)`"
  ]
}

Usage

utld

import { utld } from "utility-class-components";

const Container = utld.div`
  flex
  text-bold
`;

// You can also extend the style of other React components.
const RedContainer = utld(Container)`
  bg-red-500
`;

ud

import { utld, ud } from "utility-class-components";

const commonStyle = ud`
  text-red-500
  hover:text-blue-500
`;

// You can nest `ud` inside other `ud` or `utld`.
const Container = utld.div`
  ${ud`
    text-red-500
    hover:text-blue-500

    ${ud`
      w-32
      h-32
    `}
  `}
`;

Array Styles

You can use array in all template literals.

const Container = utld.div`
  ${["flex flex-col", "text-red-500"]}
`;

You can also use nested arrays.

const Container = utld.div`
  ${["flex flex-col", ["text-bold", "text-red-500"]]}
`;

Pass Props to Component

You can pass props to the utld component using generics.

const Container = utld.div<{ $type: "red" | "blue" }>`
  ${({ $type }) => ($type === "red" ? "bg-red-500" : "bg-blue-500")}
  w-32
  h-32
`;

const Page = () => {
  return <Container $type='red'>Hello</Container>;
};

This also can be done using another React component.

const Box = ({ className }: { className?: string }) => {
  return <div className={className}>Hello</div>;
};

const Container = utld(Box)<{ $type: "red" | "blue" }>`
  ${({ $type }) => ($type === "red" ? "bg-red-500" : "bg-blue-500")}
  w-32
  h-32
`;

const Page = () => {
  return <Container $type='red'>Hello</Container>;
};

Currently, this feature is not available in ud.

Make sure certain props are not passed or rendered

If you want to prevent certain props from being passed to an underlying React component or rendered on a DOM element, you can prefix the prop name with a $ (dollar sign).

const Box = utld.div<{ $isRed: boolean }>`
  ${({ $isRed }) => $isRed && "bg-red-500"}
  w-32
  h-32
`;
// `$isRed` prop will not be rendered in the DOM

This feature is useful when you encounter the warning React does not recognize the X prop on a DOM element.

Handle ForwardRefExoticComponent

You can also pass a ForwardRefExoticComponent to utld, which can be created using React.forwardRef.

const ForwardedInput = React.forwardRef<HTMLInputElement, ComponentPropsWithoutRef<"input">>(
  (props, ref) => {
    return <input ref={ref} {...props} />;
  },
);

const Input = utld(ForwardedInput)`
  bg-red-500
`;

const Page = () => {
  const inputRef = React.useRef<HTMLInputElement>(null);

  return <Input ref={inputRef} />;
};

Experimental Features

Grouping Variants

You can group variants in the following way :

export const Link = utld.a`
  hover:(text-accent-light dark:text-accent-dark)
`;

// Line breaks can also be added
export const Box = utld.div`
  hover:(
    text-accent-light
    dark:text-accent-dark
  )
`;

// You can nest grops
export const NestedBox = utld.div`
  hover:(
    text-accent-light
    dark:(
      text-accent-dark
      bg-red-500
    )
  )
`;

During runtime, this will be transformed into "transition-colors hover:text-accent-light hover:dark:text-accent-dark)".

To enable this feature, you need to add a transformer to the utility class library you are using. This transformer will allow the library to generate styles for hover:text-accent-light hover:dark:text-accent-dark.

For example, if you are using TailwindCSS, you can add the following code to your tailwind.config.js file:

const { transformGroupSelector } = require("utility-class-components");

module.exports = {
  content: {
    files: [
      // your target files
    ],
    transform: {
      tsx: (code) => {
        code = transformGroupSelector(code);
        return code;
      },
      // add jsx if you are using it
    },
  },
  // ...
};

CAUTION: This may cause some issues.

Disabling cssConflict lint warning

Furthermore, you should add the following configuration to your VSCode settings.json file:

{
  "tailwindCSS.lint.cssConflict": "ignore"
}

This is necessary because Tailwind CSS IntelliSense is not aware of how grouping variants work. Please note that by disabling this lint, you will not receive warnings if you attempt to set conflicting styles.

const Page = () => {
  // The following className will not trigger a lint warning anymore.
  return <div className='text-red-500 text-blue-500'>No Warning</div>;
};

Acknowledgments

Avoid constructing class names dynamically

When using utility class libraries, it's important to note that dynamic styles cannot be used due to the limitations of such libraries.

const style = `w-${width}`; // ❌

const style = "w-[100px]"; // 👌👌

Override Style using !

To override the style of a utility class library, you may need to use the !important declaration.

Using libraries like tailwind-merge could be a good option. However, since this library is not exclusively designed for Tailwind CSS, such a feature is not included.

const Box = utld.div`
  bg-red-500
`;

const StyledBox = utld(Box)`
  !bg-green-500
`;
// You should use `!` to override the background color