I started developing a React component library and wanted to reuse some SCSS code we shared with other non-React projects.
To achieve this, I tried using SASS modules in a React component.
Simple use case works fine, but I'm creating a component library and I need multiple style combinations for certain components like buttons.
Now, I have a problem with the Button
component. The component is very simple, but it has 3 different variant
values.
This is Button.tsx
file:
import React from "react"; import styles from "./Button.module.scss"; type Variant = "default" | "primary" | "tertiary"; interface Props { children: String; variant: Variant; } export const Button: React.FC<Props> = ({ children, variant }) => { return <button className={`${styles.button} ${variant}`}>{children}</button>; };
This is Button.module.scss
File:
.button { border: none; padding: 0.5rem 1.5rem; border-radius: 0.25rem; background-color: grey; color: white; &.default { background-color: green; } &.primary { background-color: red; } }
What I expected is that if I use a component like <Buttonvariant="default">I'm green</Button>
there will be a green button, but what I get is Gray button.
This is an example on codesandbox
I'm stuck on this issue, can anyone help me apply different styles based on prop value?
Please use
classnames
npm library.