What I Want:
I have a Button component, which accepts a variant prop. I want the className for the button to change based on the prop passed to it.
The goal is to avoid using if/else statements buttons, instead using a single button that dynamically changes based on the need.
Things to Note:
- I'm using Tailwindcss as the primary styling engine.
Ideal Solution:
// provide the variant to component:
<Button variant="default" />
// would return:
<button className={variantClasses.default} />
Button Component:
interface Props {
variant: string;
innerText: string;
}
function Button({ variant, innerText }: Props) {
// classes for all variants
const variantClasses = {
error: "...classes",
default: "...classes",
};
// if no variant provided, return an error variant.
if (!variant) {
return <button className={variantClasses.error}>Error</button>;
}
// else return the correct variant with matching styles.
else {
return (
<button className={`${variantClasses}.${variant}`}>
{innerText || "Button"}
</button>
);
}
}
export default Button;
What I've Tried:
- Changing the interpolation values inside button
className. - Using an array for
variantClassesinstead of an object.