React component library + SASS modularity
P粉818306280
P粉818306280 2024-03-26 21:31:03
0
2
426

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?

P粉818306280
P粉818306280

reply all(2)
P粉504080992

Please use classnames npm library.

import cn from 'classnames';

P粉244155277
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template