mui / pigment-css

Pigment CSS is a zero-runtime CSS-in-JS library that extracts the colocated styles to their own CSS files at build time.
MIT License
396 stars 19 forks source link

Dynamic style with `css` function #86

Open Ardear opened 1 month ago

Ardear commented 1 month ago

Steps to reproduce

  1. Clone the example pigment-css-nextjs-ts
  2. Create a component as :
    
    import { css } from "@pigment-css/react";
    import { FunctionComponent } from "react";

interface ButtonProps { width: string; }

export const Button: FunctionComponent = ({ width, }) => { return ( <div className={${css({ width, height: "fit-content", padding: "10px", border: "1px solid white", borderRadius: 4, })}}

Button

); };

3. Use the component :

// src/app/page.tsx

export default function Home() { return (

oliviertassinari commented 1 month ago

It sounds like at the very minimum, a lack of docs for this topic, e.g. https://github.com/callstack/linaria/blob/master/docs/DYNAMIC_STYLES.md.

However, I don't think that it's good enough, we also want to be able to use theme tokens. But then, I would imagine it's about using CSS Variables, e.g. style={{ padding: `calc(var(--pig-spacing-1) * ${unit})`, }}.

brijeshb42 commented 1 month ago

True. We need to update documentation around using runtime variables to define styles.

@Ardear This will work if you instead create a styled wrapper for the same component:

const ButtonWrapped = styled.button<{width: number}>({
  width: (props) => props.width,
  height: "fit-content",
  padding: "10px",
  border: "1px solid white",
  borderRadius: 4,
});

// and use it like this

interface ButtonProps {
  width: string;
}

export const Button: FunctionComponent<ButtonProps> = ({
  width,
}) => {
  return (
    <ButtonWrapped width={width}>
      Button
    </ButtonWrapped>
  );
};

Pigment CSS expects most of the css values to be static, one of the reasons to defined styled components or css calls at the file scope, instead of being inside a function. To apply dynamic width, use the callback signature as shown above. This way, it's able to extract the css at build time while not failing for dynamic values.

Ardear commented 1 month ago

@brijeshb42 Yeah, I understand the styled API example. But I'm using css function before, it takes a little work to move to styled, I'll think about it.

o-alexandrov commented 6 days ago

You don’t need to move to styled. You can use css for className prop and style prop for inline styles.