Skip to content

Commit 2af0072

Browse files
siriwatknpmnajdova
authored andcommitted
[docs][pigment] Add example and guide section (mui#41249)
1 parent 9fff3de commit 2af0072

File tree

1 file changed

+143
-6
lines changed

1 file changed

+143
-6
lines changed

packages/pigment-react/README.md

Lines changed: 143 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Pigment CSS
22

3-
A zero-runtime CSS-in-JS library that extracts the colocated styles to their own CSS files at build-time.
3+
Pigment CSS is a zero-runtime CSS-in-JS library that extracts the colocated styles to their own CSS files at build time.
44

55
- [Getting started](#getting-started)
66
- [Why this project exists?](#why-choose-pigment-css)
@@ -19,6 +19,8 @@ A zero-runtime CSS-in-JS library that extracts the colocated styles to their own
1919
- [Color schemes](#color-schemes)
2020
- [Switching color schemes](#switching-color-schemes)
2121
- [TypeScript](#typescript)
22+
- [How-to guides](#how-to-guides)
23+
- [Coming from Emotion or styled-components](#coming-from-emotion-or-styled-components)
2224

2325
## Getting started
2426

@@ -142,7 +144,7 @@ Use the `variants` key to define styles for a combination of the component's pro
142144

143145
Each variant is an object with `props` and `style` keys. The styles are applied when the component's props match the `props` object.
144146

145-
**Example 1**: A button component with `small` and `large` sizes:
147+
**Example 1** A button component with `small` and `large` sizes:
146148

147149
```jsx
148150
const Button = styled('button')({
@@ -166,7 +168,7 @@ const Button = styled('button')({
166168
<Button size="small">Small button</Button>; // padding: 0.5rem
167169
```
168170

169-
**Example 2**: A button component with variants and colors:
171+
**Example 2** A button component with variants and colors:
170172

171173
```jsx
172174
const Button = styled('button')({
@@ -187,7 +189,7 @@ const Button = styled('button')({
187189
</Button>;
188190
```
189191

190-
**Example 3**: Apply styles based on a condition:
192+
**Example 3** Apply styles based on a condition:
191193

192194
The value of the `props` can be a function that returns a boolean. If the function returns `true`, the styles are applied.
193195

@@ -205,6 +207,37 @@ const Button = styled('button')({
205207
});
206208
```
207209

210+
Note that the `props` function will not work if it is inside another closure, for example, inside an `array.map`:
211+
212+
```jsx
213+
const Button = styled('button')({
214+
border: 'none',
215+
padding: '0.75rem',
216+
// ...other base styles
217+
variants: ['red', 'blue', 'green'].map((item) => ({
218+
props: (props) => {
219+
// ❌ Cannot access `item` in this closure
220+
return props.color === item && !props.disabled;
221+
},
222+
style: { backgroundColor: 'tomato' },
223+
})),
224+
});
225+
```
226+
227+
Instead, use plain objects to define the variants:
228+
229+
```jsx
230+
const Button = styled('button')({
231+
border: 'none',
232+
padding: '0.75rem',
233+
// ...other base styles
234+
variants: ['red', 'blue', 'green'].map((item) => ({
235+
props: { color: item, disabled: false },
236+
style: { backgroundColor: 'tomato' },
237+
})),
238+
});
239+
```
240+
208241
#### Styling based on runtime values
209242

210243
> 💡 This approach is recommended when the value of a prop is **unknown** ahead of time or possibly unlimited values, e.g. styling based on the user's input.
@@ -217,7 +250,7 @@ const Heading = styled('h1')({
217250
});
218251
```
219252

220-
Zero-runtime will replace the callback with a CSS variable and inject the value through inline style. This makes it possible to create a static CSS file while still allowing dynamic styles.
253+
Pigment CSS will replace the callback with a CSS variable and inject the value through inline style. This makes it possible to create a static CSS file while still allowing dynamic styles.
221254

222255
```css
223256
.Heading_class_akjsdfb {
@@ -322,7 +355,7 @@ const Heading = styled('h1')(({ theme }) => ({
322355

323356
#### CSS variables support
324357

325-
Zero-runtime can generate CSS variables from the theme values when you wrap your theme with `extendTheme` utility. For example, in a `next.config.js` file:
358+
Pigment CSS can generate CSS variables from the theme values when you wrap your theme with `extendTheme` utility. For example, in a `next.config.js` file:
326359

327360
```js
328361
const { withPigment, extendTheme } = require('@pigment-css/nextjs-plugin');
@@ -461,3 +494,107 @@ declare module '@pigment-css/react/theme' {
461494
}
462495
}
463496
```
497+
498+
## How-to guides
499+
500+
### Coming from Emotion or styled-components
501+
502+
Emotion and styled-components are runtime CSS-in-JS libraries. What you write in your styles is what you get in the final bundle, which means the styles can be as dynamic as you want with bundle size and performance overhead trade-offs.
503+
504+
On the other hand, Pigment CSS extracts CSS at build time and replaces the JS code with hashed class names and some CSS variables. This means that it has to know all of the styles to be extracted ahead of time, so there are rules and limitations that you need to be aware of when using JavaScript callbacks or variables in Pigment CSS's APIs.
505+
506+
Here are some common patterns and how to achieve them with Pigment CSS:
507+
508+
1. **Fixed set of styles**
509+
510+
In Emotion or styled-components, you can use props to create styles conditionally:
511+
512+
```js
513+
const Flex = styled('div')((props) => ({
514+
display: 'flex',
515+
...(props.vertical // ❌ Pigment CSS will throw an error
516+
? {
517+
flexDirection: 'column',
518+
paddingBlock: '1rem',
519+
}
520+
: {
521+
paddingInline: '1rem',
522+
}),
523+
}));
524+
```
525+
526+
But in Pigment CSS, you need to define all of the styles ahead of time using the `variants` key:
527+
528+
```js
529+
const Flex = styled('div')((props) => ({
530+
display: 'flex',
531+
variants: [
532+
{
533+
props: { vertical: true },
534+
style: {
535+
flexDirection: 'column',
536+
paddingBlock: '1rem',
537+
},
538+
},
539+
{
540+
props: { vertical: false },
541+
style: {
542+
paddingInline: '1rem',
543+
},
544+
},
545+
],
546+
}));
547+
```
548+
549+
> 💡 Keep in mind that the `variants` key is for fixed values of props, for example, a component's colors, sizes, and states.
550+
551+
2. **Programatically generated styles**
552+
553+
For Emotion and styled-components, the styles will be different on each render and instance because the styles are generated at runtime:
554+
555+
```js
556+
function randomBetween(min: number, max: number) {
557+
return Math.floor(Math.random() * (max - min + 1) + min);
558+
}
559+
function generateBubbleVars() {
560+
return `
561+
--x: ${randomBetween(10, 90)}%;
562+
--y: ${randomBetween(15, 85)}%;
563+
`;
564+
}
565+
566+
function App() {
567+
return (
568+
<div>
569+
{[...Array(10)].map((_, index) => (
570+
<div key={index} className={css`${generateBubbleVars()}`} />
571+
))}
572+
</div>
573+
)
574+
}
575+
```
576+
577+
However, in Pigment CSS with the same code as above, all instances will have the same styles and won't change between renders because the styles are extracted at build time.
578+
579+
To achieve the same result, you need to move the dynamic logic to props and pass the value to CSS variables instead:
580+
581+
```js
582+
function randomBetween(min: number, max: number) {
583+
return Math.floor(Math.random() * (max - min + 1) + min);
584+
}
585+
586+
const Bubble = styled('div')({
587+
'--x': props => props.x,
588+
'--y': props => props.y,
589+
});
590+
591+
function App() {
592+
return (
593+
<div>
594+
{[...Array(10)].map((_, index) => (
595+
<Bubble key={index} x={`${randomBetween(10, 90)}%`} y={`${randomBetween(15, 85)}%`} />
596+
))}
597+
</div>
598+
)
599+
}
600+
```

0 commit comments

Comments
 (0)