From 13a36f77f01445028a566514e76fd1ba2598efbd Mon Sep 17 00:00:00 2001 From: Siriwat K Date: Fri, 8 Mar 2024 10:40:45 +0700 Subject: [PATCH] [docs][pigment] Add example and guide section (#41249) --- packages/pigment-react/README.md | 149 +++++++++++++++++++++++++++++-- 1 file changed, 143 insertions(+), 6 deletions(-) diff --git a/packages/pigment-react/README.md b/packages/pigment-react/README.md index 74c5468d771e95..afca1fa7e9e461 100644 --- a/packages/pigment-react/README.md +++ b/packages/pigment-react/README.md @@ -1,6 +1,6 @@ # Pigment CSS -A zero-runtime CSS-in-JS library that extracts the colocated styles to their own CSS files at build-time. +Pigment CSS is a zero-runtime CSS-in-JS library that extracts the colocated styles to their own CSS files at build time. - [Getting started](#getting-started) - [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 - [Color schemes](#color-schemes) - [Switching color schemes](#switching-color-schemes) - [TypeScript](#typescript) +- [How-to guides](#how-to-guides) + - [Coming from Emotion or styled-components](#coming-from-emotion-or-styled-components) ## Getting started @@ -142,7 +144,7 @@ Use the `variants` key to define styles for a combination of the component's pro Each variant is an object with `props` and `style` keys. The styles are applied when the component's props match the `props` object. -**Example 1**: A button component with `small` and `large` sizes: +**Example 1** — A button component with `small` and `large` sizes: ```jsx const Button = styled('button')({ @@ -166,7 +168,7 @@ const Button = styled('button')({ ; // padding: 0.5rem ``` -**Example 2**: A button component with variants and colors: +**Example 2** — A button component with variants and colors: ```jsx const Button = styled('button')({ @@ -187,7 +189,7 @@ const Button = styled('button')({ ; ``` -**Example 3**: Apply styles based on a condition: +**Example 3** — Apply styles based on a condition: The value of the `props` can be a function that returns a boolean. If the function returns `true`, the styles are applied. @@ -205,6 +207,37 @@ const Button = styled('button')({ }); ``` +Note that the `props` function will not work if it is inside another closure, for example, inside an `array.map`: + +```jsx +const Button = styled('button')({ + border: 'none', + padding: '0.75rem', + // ...other base styles + variants: ['red', 'blue', 'green'].map((item) => ({ + props: (props) => { + // ❌ Cannot access `item` in this closure + return props.color === item && !props.disabled; + }, + style: { backgroundColor: 'tomato' }, + })), +}); +``` + +Instead, use plain objects to define the variants: + +```jsx +const Button = styled('button')({ + border: 'none', + padding: '0.75rem', + // ...other base styles + variants: ['red', 'blue', 'green'].map((item) => ({ + props: { color: item, disabled: false }, + style: { backgroundColor: 'tomato' }, + })), +}); +``` + #### Styling based on runtime values > 💡 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')({ }); ``` -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. +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. ```css .Heading_class_akjsdfb { @@ -322,7 +355,7 @@ const Heading = styled('h1')(({ theme }) => ({ #### CSS variables support -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: +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: ```js const { withPigment, extendTheme } = require('@pigment-css/nextjs-plugin'); @@ -461,3 +494,107 @@ declare module '@pigment-css/react/theme' { } } ``` + +## How-to guides + +### Coming from Emotion or styled-components + +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. + +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. + +Here are some common patterns and how to achieve them with Pigment CSS: + +1. **Fixed set of styles** + +In Emotion or styled-components, you can use props to create styles conditionally: + +```js +const Flex = styled('div')((props) => ({ + display: 'flex', + ...(props.vertical // ❌ Pigment CSS will throw an error + ? { + flexDirection: 'column', + paddingBlock: '1rem', + } + : { + paddingInline: '1rem', + }), +})); +``` + +But in Pigment CSS, you need to define all of the styles ahead of time using the `variants` key: + +```js +const Flex = styled('div')((props) => ({ + display: 'flex', + variants: [ + { + props: { vertical: true }, + style: { + flexDirection: 'column', + paddingBlock: '1rem', + }, + }, + { + props: { vertical: false }, + style: { + paddingInline: '1rem', + }, + }, + ], +})); +``` + +> 💡 Keep in mind that the `variants` key is for fixed values of props, for example, a component's colors, sizes, and states. + +2. **Programatically generated styles** + +For Emotion and styled-components, the styles will be different on each render and instance because the styles are generated at runtime: + +```js +function randomBetween(min: number, max: number) { + return Math.floor(Math.random() * (max - min + 1) + min); +} +function generateBubbleVars() { + return ` + --x: ${randomBetween(10, 90)}%; + --y: ${randomBetween(15, 85)}%; + `; +} + +function App() { + return ( +
+ {[...Array(10)].map((_, index) => ( +
+ ))} +
+ ) +} +``` + +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. + +To achieve the same result, you need to move the dynamic logic to props and pass the value to CSS variables instead: + +```js +function randomBetween(min: number, max: number) { + return Math.floor(Math.random() * (max - min + 1) + min); +} + +const Bubble = styled('div')({ + '--x': props => props.x, + '--y': props => props.y, +}); + +function App() { + return ( +
+ {[...Array(10)].map((_, index) => ( + + ))} +
+ ) +} +```