platform-bible-react
    Preparing search index...

    Function cn

    • Tailwind and CSS class application helper function. Uses clsx to make it easy to apply classes conditionally using object syntax, and uses tailwind-merge to make it easy to merge/overwrite Tailwind classes in a programmer-logic-friendly way.

      Supports both TW3 (tw-*) and TW4 (tw:*) prefix formats. When classes using different prefix formats conflict (e.g. tw-p-4 vs tw:p-4), the last one specified wins (standard tailwind-merge behavior), and the result preserves the winning class's original prefix format.

      This backwards compatibility allows extensions still using TW3's tw- prefix to interoperate with PBR components that have migrated to TW4's tw: prefix.

      This function was popularized by shadcn/ui. See ByteGrad's explanation video for more information.

      Parameters

      • ...inputs: ClassValue[]

        Class strings or clsx conditional class objects to merge. Tailwind classes specified later in the arguments overwrite similar Tailwind classes specified earlier in the arguments

      Returns string

      Class string containing all applicable classes from the arguments based on the rules described above

      const borderShouldBeBlue = true;
      const textShouldBeRed = true;
      const heightShouldBe20 = false;
      const classString = cn(
      'tw:bg-primary tw:h-10 tw:text-primary-foreground',
      'tw:bg-secondary',
      {
      'tw:border-blue-500': borderShouldBeBlue,
      'tw:text-red-500': textShouldBeRed,
      'tw:h-20': heightShouldBe20,
      },
      'some-class',
      );

      The resulting classString is 'tw:h-10 tw:bg-secondary tw:border-blue-500 tw:text-red-500 some-class'

      • Notice that 'tw:bg-secondary', specified later, overwrote 'tw:bg-primary', specified earlier, because they are Tailwind classes that affect the same css property
      • Notice that 'tw:text-red-500', specified later, overwrote 'tw:text-primary-foreground', specified earlier, because they are Tailwind classes that affect the same css property
      • Notice that 'tw:h-20', specified later, did not overwrite 'tw:h-10', specified earlier, because 'tw:h-20' is part of a conditional class object and its value evaluated to false; therefore it was not applied
      • Notice that 'some-class' was applied. This function is not limited only to Tailwind classes.