javascriptcsstypescripttailwind-cssclsx

Create a styling rule for clsx for React + Typescript


Having this clsx method which works fine:

const getLinkClasses = (disabled: boolean) => {
  return clsx('flex whitespace-nowrap', {
    'text-gray-500': !disabled,
    'text-gray-300 cursor-not-allowed': disabled
  });
};

There are two other optional variables, one for disabled and one for !disabled that are strings and can add new rules to the above method. Let's call them disabledValue and notDisabledValue.

For example,

const disabledValue = 'bg-red-100'; 
const notDisabledValue = 'bg-green-100';

In order to add those variables, I've made the following changes:

export interface MyProps {
  disabledValue?: string;
  notDisabledValue?: string;
}

const getLinkClasses = (disabled: boolean, style: MyProps) => {
  const notDis = `text-gray-500 ${style.notDisabledValue ?? ''}`;
  const dis = `text-gray-300 cursor-not-allowed ${style.disabledValue ?? ''}`;

  return clsx('flex whitespace-nowrap', {
    notDis: !disabled,
    dis: disabled
  });
};

The problem is that those two variables, notDis and dis aren't read:

'notDis' is declared but its value is never read.ts(6133)

'notDis' is assigned a value but never used.eslint@typescript-eslint/no-unused-vars

Is there a way to fix it?


Solution

  • The problem is that you want to use "computed property names".

    Something like this in ES6+:

    const getLinkClasses = (disabled: boolean, style: MyProps) => {
      const notDis = `text-gray-500 ${style.notDisabledValue ?? ''}`;
      const dis = `text-gray-300 cursor-not-allowed ${style.disabledValue ?? ''}`;
    
      return clsx('flex whitespace-nowrap', {
        [notDis]: !disabled,
        [dis]: disabled
      });
    };
    

    See: JavaScript set object key by variable