I have a react component with fairly complicated design, styled by tailwind and want to make it reusable with different styles depending on the value of its parameter which called variant.
what is the best practice in this situation?
1- make a general class then add different css classes in @layer components, one class for each design.
2- change the style directly in the react component using twMerge and clsx depending on the parameter which i mentioned earlier.
3- use styled-components with tailwindCss
Asked
Active
Viewed 166 times
0

Lana Hanna
- 91
- 1
- 9
-
1There are a couple of good articles on creating Tailwind CSS UI components here which may help: https://www.protailwind.com/articles – stickyuser Jun 05 '23 at 15:43
1 Answers
0
This is the way I like to do it as it's clean.
You can also add this to your VSCode settings if you'd like to have intellisense for custom classes. It works by detecting anything ending in 'classes' as Tailwind styles.
`
"tailwindCSS.experimental.classRegex": [
[
"Classes \\=([^;]*);",
"'([^']*)'"
],
[
"Classes \\=([^;]*);",
"\"([^\"]*)\""
],
[
"Classes \\=([^;]*);",
"\\`([^\\`]*)\\`"
]
],
`
Create a component
import React from "react";
import { twMerge } from "tailwind-merge";
const baseClasses = `
min-w-[220px] px-8 py-4
text-base leading-5 font-semibold
border-none rounded-md
cursor-pointer
disabled:opacity-50
`;
const variationClasses = {
"black-on-green": `
${ baseClasses }
text-zinc-700
bg-emerald-300
`
};
interface Props extends React.ButtonHTMLAttributes<HTMLButtonElement> {
children: React.ReactNode;
className?: string;
variation: keyof typeof variationClasses;
}
const CustomButton = React.forwardRef<HTMLButtonElement, Props>(({ children, className, variation, ...rest }, ref) => {
return(
<button
className={ twMerge(variationClasses[variation], className) }
ref={ ref }
type="submit"
{ ...rest }>
{ children }
</button>
);
});
CustomButton.displayName = "CustomButton";
export { CustomButton };

P Savva
- 309
- 1
- 5