skip to Main Content

I’ve uploaded my first React component to NPM. It’s a slider with ticks (fractions) that you can drag.

Here’s the link: Fractional Range Slider NPM

I’ve made it up with TailwindCSS. When it is bundled, it generates all the classes being used. The first problem was that when the package was installed in a project, the prebundled classes overrided the new ones being generated in real time. I fixed it adding prefixes to the Tailwind configuration:

// tailwind.config.js

module.exports = {
  content: ["./src/**/*.tsx"],
  prefix: "fr-",
  // ...
};

Though it has worked, now I have a new problem.

I use a utility function to deal with Tailwind classes conflicts in order to make the component extensible:

import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'

/**
 * Merge conflicting tailwind classes
 * @param inputs
 * @returns
 */
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

Since the Tailwind classes are different (the package ones have the prefix and the ones being passed not), the utility function no longer merge them and thus, the new classes that conflicts are overrided again.

Maybe hardcoding a filter with the prefix in the utility function could work before doing the checks, but, there is any proven or great solution to this?

Thanks in advance!

2

Answers


  1. You need to make some changes as bellow:

    import { type ClassValue, clsx } from 'clsx'
    import { twMerge } from 'tailwind-merge'
    
    /**
     * Merge conflicting tailwind classes
     * @param inputs
     * @returns
     */
    export function cn(...inputs: ClassValue[]) {
      let clsxOutputArray = clsx(inputs).split(" "); // output from clsx function
      let currentClassList = clsxOutputArray.filter((c) => c.startsWith("fr-")); // classes with prefix 'fr-'
      let twMergedClassList = twMerge(
        [...clsxOutputArray].map((c) => {
          // adding prefix to normal tailwind classes to get merged with classes with prefix
          if (!c.startsWith("fr-")) {
            return "fr-".concat(c);
          }
          return c;
        }),
      )
        .split(" ")
        .map((c) => {
          if (!currentClassList.includes(c)) {
            // removing prefix from the classes that are not belong to your package
            return c.replace("fr-", "");
          }
          return c;
        })
        .join(" ");
      return twMergedClassList;
    }
    

    Changes:

    • Removing prefix from classNames
    Login or Signup to reply.
  2. I think:

    import { twMerge } from 'tailwind-merge'
    
    /**
     * Merge conflicting tailwind classes
     * @param inputs
     * @returns
     */
    export function cn(...inputs: ClassValue[]) {
      return twMerge(clsx(inputs).replaceAll('fr-', ''))
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search