### Install and Configure Babel Plugin for Styled Components Source: https://styled-components.com/docs/tooling Installs the babel-plugin-styled-components and configures it in the Babel setup. This plugin enhances server-side rendering, style minification, and debugging. ```bash npm install --save-dev babel-plugin-styled-components ``` ```json { "plugins": ["babel-plugin-styled-components"] } ``` -------------------------------- ### Install styled-components Source: https://styled-components.com/docs/basics Commands to install the library using npm or yarn package managers. ```bash npm install styled-components yarn add styled-components ``` -------------------------------- ### Install Stylelint Dependencies Source: https://styled-components.com/docs/tooling Installs the required Stylelint packages and configurations for styled-components via npm. ```bash npm install --save-dev stylelint stylelint-processor-styled-components stylelint-config-styled-components stylelint-config-recommended ``` -------------------------------- ### Tooling Setup (Babel/SWC Plugins) Source: https://styled-components.com/docs/advanced Provides information on setting up Babel or SWC plugins for styled-components to ensure deterministic component IDs for SSR consistency, minification, and better debugging. ```APIDOC ## Tooling Setup (Babel/SWC Plugins) ### Description To ensure deterministic component IDs for server/client consistency, use our Babel plugin or SWC plugin. Both provide equivalent functionality including SSR support, minification, and better debugging. For React Server Components (v6.3.0+), these plugins are optional for SSR but still offer minification and debugging benefits. ### Method N/A (Configuration) ### Endpoint N/A ### Parameters N/A ### Request Example #### Babel Plugin Configuration Add to your `.babelrc` or `babel.config.js`: ```json { "plugins": ["styled-components"] } ``` #### SWC Plugin Configuration (for Next.js) Add to your `next.config.js`: ```javascript module.exports = { compiler: { styledComponents: true, }, }; ``` ### Response #### Success Response (200) N/A (Configuration) #### Response Example N/A ``` -------------------------------- ### Install styled-theming Package Source: https://styled-components.com/docs/tooling Command to install the styled-theming package, which helps in creating themes for styled components. This package is no longer actively maintained, and using the built-in theming API is recommended for new projects. ```bash npm install --save styled-theming ``` -------------------------------- ### Configure Monorepo Dependencies Source: https://styled-components.com/docs/faqs Example of a root package.json configuration for a monorepo to ensure styled-components is hoisted and shared across workspaces. ```json { "name": "my-styled-monorepo", "dependencies": { "styled-components": "^6" }, "scripts": { "start": "turbo run start", "build": "turbo run build" } } ``` -------------------------------- ### Install styled-components v6 Source: https://styled-components.com/docs/faqs Commands to install the latest version of styled-components and remove legacy community type definitions. ```bash npm install styled-components@^6 stylis@^4 npm uninstall @types/styled-components ``` ```bash yarn add styled-components@^6 stylis@^4 yarn remove @types/styled-components ``` -------------------------------- ### Adapting Styles with Props Source: https://styled-components.com/docs/basics This example demonstrates how to create a Button component that changes its background and text color based on a `$primary` prop. ```APIDOC ## Adapting Styles with Props ### Description This endpoint demonstrates how to create a Button component that changes its background and text color based on a `$primary` prop. When the `$primary` prop is set to true, the button's appearance is altered. ### Method N/A (This is a conceptual example, not an API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```jsx const Button = styled.button<{ $primary?: boolean; }>` /* Adapt the colors based on primary prop */ background: ${props => props.$primary ? "#BF4F74" : "white"}; color: ${props => props.$primary ? "white" : "#BF4F74"}; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid #BF4F74; border-radius: 3px; `; render(
); ``` ### Response #### Success Response (200) N/A (This is a UI component example) #### Response Example N/A ``` -------------------------------- ### Styled Components Theming Example with styled-theming Source: https://styled-components.com/docs/tooling An example demonstrating how to use the styled-theming package with React and styled-components to create dynamic theming. It defines a Box component whose background color changes based on the 'mode' theme property. ```javascript import React from 'react' import styled, { ThemeProvider } from 'styled-components' import theme from 'styled-theming' const boxBackgroundColor = theme('mode', { light: '#fff', dark: '#000', }) const Box = styled.div` background-color: ${boxBackgroundColor}; ` export default function App() { return ( Hello World ) } ``` -------------------------------- ### Configure styled-components with Vite and SWC Source: https://styled-components.com/docs/tooling Installs and configures the SWC-based React plugin for Vite to support styled-components. This setup enables SSR, component display names, and CSS minification. ```bash npm install --save-dev @vitejs/plugin-react-swc @swc/plugin-styled-components ``` ```typescript import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react-swc'; export default defineConfig({ plugins: [ react({ plugins: [ ['@swc/plugin-styled-components', { displayName: true, ssr: true, }], ], }), ], }); ``` -------------------------------- ### Configure SWC Plugin for styled-components Source: https://styled-components.com/docs/tooling Installs and configures the SWC plugin directly in the .swcrc file for projects using the SWC compiler. ```bash npm install --save-dev @swc/plugin-styled-components @swc/core ``` ```json { "jsc": { "experimental": { "plugins": [ [ "@swc/plugin-styled-components", { "displayName": true, "ssr": true } ] ] } } } ``` -------------------------------- ### Basic Theming with ThemeProvider Source: https://styled-components.com/docs/advanced Demonstrates how to use the ThemeProvider to pass a theme object down to styled components. Components can access theme properties via props.theme. This example shows a Button component styled using theme colors. ```javascript const Button = styled.button` font-size: 1em; margin: 1em; padding: 0.25em 1em; border-radius: 3px; /* Color the border and text with theme.main */ color: ${props => props.theme?.main || '#BF4F74'}; border: 2px solid ${props => props.theme?.main || '#BF4F74'}; `; const theme = { main: "mediumseagreen" }; render(
); ``` -------------------------------- ### Basic Interpolation Example in Styled Components Source: https://styled-components.com/docs/tooling Demonstrates a basic styled-component with a variable interpolation that might cause issues with stylelint without proper tagging. The processor attempts to guess the interpolation type, which can sometimes be incorrect. ```javascript const something = 'background'; const Button = styled.div` ${something}: papayawhip; `; ``` -------------------------------- ### Install Dependencies for v5 Migration Source: https://styled-components.com/docs/faqs Command to upgrade styled-components and required React peer dependencies to version 5.0.0. Ensure React Native projects are at least v0.59 for hooks support. ```bash npm install styled-components@^5.0.0 react@^16.8 react-dom@^16.8 react-is@^16.8 ``` -------------------------------- ### Function Themes with ThemeProvider Source: https://styled-components.com/docs/advanced Illustrates how to use a function for the theme prop in ThemeProvider. This function receives the parent theme and can create a new theme, allowing for contextual theming. The example shows inverting foreground and background colors. ```javascript const Button = styled.button` color: ${props => props.theme.fg}; border: 2px solid ${props => props.theme.fg}; background: ${props => props.theme.bg}; font-size: 1em; margin: 1em; padding: 0.25em 1em; border-radius: 3px; `; const theme = { fg: "#BF4F74", bg: "white" }; const invertTheme = ({ fg, bg }) => ({ fg: bg, bg: fg }); render(
); ``` -------------------------------- ### Maintaining Accessibility with Semantic Elements Source: https://styled-components.com/docs/advanced Provides examples of using semantic HTML elements as base components and utilizing the 'as' prop to change element semantics while preserving styles. ```javascript const Nav = styled.nav`...`; const Button = styled.button`...`; const Text = styled.p`font-size: 1rem; line-height: 1.5;`; Name; ``` -------------------------------- ### Shorthand Interpolation Tagging (sc-sel) Source: https://styled-components.com/docs/tooling Provides an example of using a shorthand tag `sc-sel` for `sc-selector` to reduce code clutter while maintaining the same functionality for indicating a CSS selector interpolation. ```javascript const Wrapper = styled.div` ${/* sc-sel */ Button} { color: red; } `; ``` -------------------------------- ### Create Styled Components with `styled.button` Source: https://styled-components.com/docs/api Demonstrates how to use the `styled` factory to create a custom styled button component and a component that extends it. It shows basic CSS application and inheritance. ```javascript // import styled from 'styled-components' const Button = styled.button` background: #BF4F74; border-radius: 3px; border: none; color: white; ` const TomatoButton = styled(Button)` background: tomato; ` render( <>
I'm red. ) ``` -------------------------------- ### Integrate CSS Framework Classes with Styled Components Source: https://styled-components.com/docs/faqs Demonstrates how to use the attrs method to attach framework classes to components by default, and how to apply additional classes via props. ```javascript const Button = styled.button.attrs(props => ({ className: "small", }))` background: black; color: white; cursor: pointer; margin: 1em; padding: 0.25em 1em; border: 2px solid black; border-radius: 3px; `; render(
); ``` -------------------------------- ### Compare Standard vs Plugin Transpilation Source: https://styled-components.com/docs/tooling Demonstrates the difference between standard Babel transpilation and the optimized output produced by the styled-components plugin. ```javascript // Standard Babel output var _templateObject = _taggedTemplateLiteral(['width: 100%;'], ['width: 100%;']) function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })) } var Simple = _styledComponents2.default.div(_templateObject) // Plugin optimized output var Simple = _styledComponents2.default.div(['width: 100%;']) ``` -------------------------------- ### Include styled-components via CDN Source: https://styled-components.com/docs/basics Instructions for using the UMD build of styled-components in environments without a module bundler. ```html ``` -------------------------------- ### The `theme` prop Source: https://styled-components.com/docs/advanced Demonstrates how to pass theme information directly to components using the `theme` prop, allowing for dynamic styling overrides or usage without a `ThemeProvider`. ```APIDOC ## The `theme` prop ### Description A theme can also be passed down to a component using the `theme` prop. This is useful to circumvent a missing `ThemeProvider` or to override it. ### Method N/A (Component Prop) ### Endpoint N/A ### Parameters #### Request Body - **theme** (object) - Required - An object containing theme properties to be applied to the component. ### Request Example ```javascript // Define our button const Button = styled.button` font-size: 1em; margin: 1em; padding: 0.25em 1em; border-radius: 3px; /* Color the border and text with theme.main */ color: ${props => props.theme.main}; border: 2px solid ${props => props.theme.main}; `; // Define what main theme will look like const theme = { main: "mediumseagreen" }; render(
); ``` ### Response #### Success Response (200) N/A (Component Rendering) #### Response Example ```html
``` ``` -------------------------------- ### Create Custom Render Wrapper for Themed Components Source: https://styled-components.com/docs/tooling Sets up a custom render utility that wraps components in a ThemeProvider, allowing tests to access theme variables. ```typescript import { render, RenderOptions } from '@testing-library/react'; import { ThemeProvider } from 'styled-components'; import { theme } from './theme'; function Providers({ children }: { children: React.ReactNode }) { return {children}; } const customRender = ( ui: React.ReactElement, options?: Omit ) => render(ui, { wrapper: Providers, ...options }); export * from '@testing-library/react'; export { customRender as render }; ``` -------------------------------- ### Extend Styled-Components DefaultTheme for TypeScript Source: https://styled-components.com/docs/api Shows how to extend the `DefaultTheme` interface in styled-components using declaration merging for TypeScript. This allows for strongly-typed themes. Examples are provided for both standard React and React Native. ```typescript import 'styled-components'; declare module 'styled-components' { export interface DefaultTheme { borderRadius: string; colors: { main: string; secondary: string; }; } } ``` ```typescript import 'styled-components/native'; declare module 'styled-components/native' { export interface DefaultTheme { borderRadius: string; colors: { main: string; secondary: string; }; } } ``` -------------------------------- ### Create Scoped Animations with Keyframes Source: https://styled-components.com/docs/basics Demonstrates how to use the keyframes helper to generate unique animation names, preventing global namespace collisions. It also shows how to apply these animations to a styled component. ```javascript const rotate = keyframes` from { transform: rotate(0deg); } to { transform: rotate(360deg); } `; const Rotate = styled.div` display: inline-block; animation: ${rotate} 2s linear infinite; padding: 2rem 1rem; font-size: 1.2rem; `; render(< 💅🏾 >); ``` -------------------------------- ### Configure ESLint for styled-components accessibility Source: https://styled-components.com/docs/advanced Install and configure eslint-plugin-styled-components-a11y to enable linting for styled components. This plugin parses tagged template literals to identify underlying HTML elements and enforce accessibility rules. ```bash npm install --save-dev eslint-plugin-styled-components-a11y ``` ```javascript import styledA11y from 'eslint-plugin-styled-components-a11y'; export default [ styledA11y.flatConfigs.recommended, ]; ``` -------------------------------- ### Incorrect Template Literal Indentation for Stylelint Source: https://styled-components.com/docs/tooling Shows examples of incorrect template literal indentation styles that may cause stylelint to fail or misinterpret the CSS. Proper indentation is crucial for the stylelint processor. ```javascript if (condition) { const Button = styled.button` color: red; ` } ``` ```javascript if (condition) { const Button = styled.button` color: red; ` } ``` -------------------------------- ### Implement Styled Components in React Native Source: https://styled-components.com/docs/basics Shows basic usage of styled-components with React Native, demonstrating how to style standard components like View and Text. ```javascript import React from 'react' import styled from 'styled-components/native' const StyledView = styled.View` background-color: papayawhip; ` const StyledText = styled.Text` color: #BF4F74; ` const MyReactNativeComponent = () => ( Hello World! ) ``` -------------------------------- ### Server Side Rendering (SSR) Source: https://styled-components.com/docs/advanced Explains how to implement server-side rendering with styled-components, including stylesheet rehydration and using `ServerStyleSheet` for concurrent rendering. ```APIDOC ## Server Side Rendering (SSR) ### Description styled-components supports concurrent server side rendering, with stylesheet rehydration. The basic idea is that every time you render your app on the server, you can create a `ServerStyleSheet` and add a provider to your React tree, that accepts styles via a context API. This doesn't interfere with global styles, such as `keyframes` or `createGlobalStyle` and allows you to use styled-components with React DOM's various SSR APIs. ### Method N/A (SSR Implementation) ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript // Example SSR setup (conceptual) import { ServerStyleSheet } from 'styled-components'; app.get('*', (req, res) => { const sheet = new ServerStyleSheet(); const html = ReactDOMServer.renderToString( sheet.collectStyles() ); const styleTags = sheet.getStyleTags(); res.send(` ${styleTags}
${html}
`); }); ``` ### Response #### Success Response (200) HTML output with injected CSS styles. #### Response Example ```html
/* Rendered React App */
``` ``` -------------------------------- ### Extending Styled Components Source: https://styled-components.com/docs/basics Demonstrates how to create a new component that inherits styles from an existing styled component using the styled() constructor. ```APIDOC ## Extending Styles ### Description Create a new component that inherits all styles from an existing styled component while allowing for property overrides. ### Usage Wrap the base component in the `styled()` constructor. ### Example ```javascript const Button = styled.button` color: #BF4F74; border: 2px solid #BF4F74; `; const TomatoButton = styled(Button)` color: tomato; border-color: tomato; `; ``` ``` -------------------------------- ### Alias styled-components with Webpack for local linking Source: https://styled-components.com/docs/faqs Configure Webpack's 'resolve.alias' option to point to the specific 'styled-components' installation in your 'node_modules'. This is crucial when using 'npm link' or 'yarn link' to ensure that all linked projects use the same instance of styled-components, preventing issues. ```javascript // const path = require('path'); { resolve: { alias: { // adjust this path as needed depending on where your webpack config is 'styled-components': path.resolve('../node_modules/styled-components') } } } ``` -------------------------------- ### Server-side Rendering Configuration Source: https://styled-components.com/docs/tooling Configure the styled-components plugin for server-side rendering. ```APIDOC ## Server-side Rendering Configuration ### Description This configuration disables the server-side rendering (SSR) checksum matching feature for styled-components. ### Method SWC Plugin Configuration ### Endpoint N/A ### Parameters #### Request Body - **`jsc.experimental.plugins`** (Array) - Required - Array of SWC plugins. - **`@swc/plugin-styled-components`** (Array) - Required - Configuration for the styled-components plugin. - **`ssr`** (Boolean) - Optional - Set to `false` to disable SSR checksum matching. Default: `true`. ### Request Example ```json { "jsc": { "experimental": { "plugins": [ [ "@swc/plugin-styled-components", { "ssr": false } ] ] } } } ``` ### Response #### Success Response (200) Configuration applied. #### Response Example N/A ``` -------------------------------- ### Accessing DOM Node Refs with `innerRef` (Deprecated) Source: https://styled-components.com/docs/api Demonstrates the use of the `innerRef` prop, deprecated in styled-components v4 in favor of the standard `ref` prop with `forwardRef`. It was used to get a direct reference to the underlying DOM node of a styled component, enabling direct DOM manipulation like focusing an input. ```javascript const Input = styled.input` padding: 0.5em; margin: 0.5em; color: #BF4F74; background: papayawhip; border: none; border-radius: 3px; ` class Form extends React.Component { render() { return ( { this.input = x }} onMouseEnter={() => this.input.focus()} /> ) } } ``` -------------------------------- ### Basic Tagged Template Literal Syntax Source: https://styled-components.com/docs/advanced Demonstrates the equivalence between tagged template literal syntax and standard function calls with arrays. ```javascript fn`some string here`; fn(['some string here']); ``` -------------------------------- ### Styled Components with Dynamic Props and Variables Source: https://styled-components.com/docs/api Illustrates using tagged template literals to create styled components with dynamic styling based on props and external variables. It shows how to interpolate variables and functions that access component props. ```javascript // import styled from 'styled-components' const padding = '3em' const Section = styled.section<{ $background?: string; }>` color: white; /* Pass variables as inputs */ padding: ${padding}; /* Adjust the background from the properties */ background: ${props => props.$background}; ` render(
✨ Magic
) ``` -------------------------------- ### Assert Styles with toHaveStyleRule Source: https://styled-components.com/docs/tooling Demonstrates how to verify CSS rules, including those inside media queries and pseudo-classes, using the toHaveStyleRule matcher. ```typescript import { render, screen } from '@testing-library/react'; import 'jest-styled-components'; const Button = styled.button` color: red; @media (max-width: 640px) { &:hover { color: green; } } `; test('applies styles and media queries', () => { render(); const button = screen.getByText('Click'); expect(button).toHaveStyleRule('color', 'red'); expect(button).toHaveStyleRule('color', 'green', { media: '(max-width: 640px)', modifier: ':hover', }); }); ``` -------------------------------- ### Enable vendor prefixes Source: https://styled-components.com/docs/faqs Restores automatic vendor prefixing in v6 by configuring the StyleSheetManager component. ```javascript import { StyleSheetManager } from 'styled-components'; function MyApp() { return ( {/* other providers or your application's JSX */} ) } ``` -------------------------------- ### Extend Styles with styled() Constructor in JavaScript Source: https://styled-components.com/docs/basics Demonstrates how to create a new styled component that inherits and overrides styles from a base component using the styled() constructor. This is useful for creating variations of existing components. ```javascript const Button = styled.button` color: #BF4F74; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 2px solid #BF4F74; border-radius: 3px; `; const TomatoButton = styled(Button)` color: tomato; border-color: tomato; `; render(
Tomato Button
); ``` -------------------------------- ### Implement theming in React Server Components Source: https://styled-components.com/docs/advanced Shows how to use CSS custom properties for theming in RSC environments, as ThemeProvider is a no-op. CSS variables are passed via the style prop to cascade styles to children. ```javascript const Container = styled.div``; const Button = styled.button` background: var(--color-primary, blue); `; ``` -------------------------------- ### Configure .stylelintrc Source: https://styled-components.com/docs/tooling Defines the processor and extended configurations required to lint styled-components. ```json { "processors": [ "stylelint-processor-styled-components" ], "extends": [ "stylelint-config-recommended", "stylelint-config-styled-components" ] } ``` -------------------------------- ### Styled Components with Typed Theme Access Source: https://styled-components.com/docs/api Demonstrates how to create styled components (`styled.div`, `createGlobalStyle`, `css` helper) that correctly access and utilize properties from a typed `DefaultTheme`. This ensures type safety for theme-related styles. ```typescript import styled, { createGlobalStyle, css } from 'styled-components'; export const MyComponent = styled.div` color: ${props => props.theme.colors.main}; `; export const MyGlobalStyle = createGlobalStyle` body { background-color: ${props => props.theme.colors.secondary}; } `; export const cssHelper = css` border: 1px solid ${props => props.theme.borderRadius}; `; ``` -------------------------------- ### ThemeProvider Component Usage Source: https://styled-components.com/docs/tooling Demonstrates the import and basic usage of the ThemeProvider component from styled-components, which is essential for styled-theming. It shows how to pass theme objects or getter functions to the theme prop. ```javascript import { ThemeProvider } from 'styled-components' ``` ```javascript ``` ```javascript modes.dark, size: sizes => sizes.large }}> ``` ```javascript function App() { return ( {/* rest of your app */} ); } ``` -------------------------------- ### NeoVim TreeSitter Configuration for Styled Components Source: https://styled-components.com/docs/tooling This configuration snippet shows how to enable syntax highlighting for styled-components in NeoVim using the TreeSitter parser. It requires adding 'styled' to the ensure_installed list in your nvim-treesitter.configs.setup. ```lua require'nvim-treesitter.configs'.setup { ensure_installed = { ..., "styled" }, highlight = { enable = true, }, } ``` -------------------------------- ### Finding Styled Component Nodes with Test Utilities Source: https://styled-components.com/docs/api The test utilities provide methods to query the DOM for rendered styled components. 'find' retrieves the first instance, while 'findAll' retrieves all instances. ```javascript import styled from 'styled-components' import { find, findAll } from 'styled-components/test-utils' const Foo = styled.div`color: red;` // Retrieve single instance find(document.body, Foo) // Retrieve all instances findAll(document.body, Foo) ``` -------------------------------- ### Basic SSR with ServerStyleSheet in React Source: https://styled-components.com/docs/advanced Demonstrates the fundamental server-side rendering approach using ServerStyleSheet to collect styles from a React application. It includes error handling and proper sealing of the sheet. ```javascript import { renderToString } from 'react-dom/server'; import { ServerStyleSheet } from 'styled-components'; const sheet = new ServerStyleSheet(); try { const html = renderToString(sheet.collectStyles()); const styleTags = sheet.getStyleTags(); // or sheet.getStyleElement(); } catch (error) { // handle error console.error(error); } finally { sheet.seal(); } ``` -------------------------------- ### Integrating Styled Components with CSS Modules Approach Source: https://styled-components.com/docs/basics Shows how to refactor a component that uses CSS Modules to use styled-components instead. This approach combines the element and its styling rules into a single styled component, offering better encapsulation and maintainability. ```javascript import React, { useState } from 'react'; import styled from 'styled-components'; const StyledCounter = styled.div` /* ... */ `; const Paragraph = styled.p` /* ... */ `; const Button = styled.button` /* ... */ `; export default function Counter() { const [count, setCount] = useState(0); return ( {count} ); } ``` -------------------------------- ### Boosting Specificity for Third-Party Style Conflicts Source: https://styled-components.com/docs/advanced Demonstrates how to avoid style conflicts with third-party styles by increasing the specificity of styled-component rules. This can be achieved using tools like `babel-plugin-styled-components-css-namespace` or by ensuring styled components have higher specificity selectors. ```css body.my-body button { padding: 24px; } ``` ```javascript styled.button` padding: 16px; ` ``` -------------------------------- ### Targeting Components with Styled Components Source: https://styled-components.com/docs/advanced Demonstrates the component selector pattern to apply styles to a child component based on the state of a parent component. This requires both components to be styled-components. ```javascript const Link = styled.a`display: flex; align-items: center; padding: 5px 10px; background: papayawhip; color: #BF4F74;`; const Icon = styled.svg`flex: none; transition: fill 0.25s; width: 48px; height: 48px; ${Link}:hover & { fill: rebeccapurple; }`; const Label = styled.span`display: flex; align-items: center; line-height: 1.2; &::before { content: '◀'; margin: 0 10px; }`; render(); ``` -------------------------------- ### Styled Components Plugin Options Source: https://styled-components.com/docs/tooling Configuration options for the styled-components SWC plugin. ```APIDOC ## Styled Components Plugin Options ### Description Configuration options for the styled-components SWC plugin. ### Options - **`displayName`** (Boolean) - Optional - Enhances the attached CSS class name on each component with richer output to help identify your components in the DOM without React DevTools. It also allows you to see the component's `displayName` in React DevTools. Default: `true`. - **`ssr`** (Boolean) - Optional - Adds a unique identifier to every styled component to avoid checksum mismatches due to different class generation on the client and on the server. Helps in server-side rendering (SSR). Default: `true`. - **`fileName`** (Boolean) - Optional - Controls whether the `displayName` of a component will be prefixed with the filename or solely the component name. Default: `true`. - **`meaninglessFileNames`** (Array of strings) - Optional - Allows customizing the list of file names that are not relevant to the description of a styled component's functionality. Uses directory names instead. Default: `["index", "styles"]`. - **`minify`** (Boolean) - Optional - Minifies your CSS by removing all whitespace and comments. Also transpiles tagged template literals to a smaller representation. Default: `true`. - **`transpileTemplateLiterals`** (Boolean) - Optional - Transpiles `styled-components` tagged template literals to a smaller representation. Helps reduce bundle size. Default: `true`. - **`pure`** (Boolean) - Optional - Enables a feature called "pure annotation" to aid dead code elimination process on styled components. Default: `false`. - **`namespace`** (String) - Optional - Ensures that your class names will be unique, useful when working with micro-frontends where class name collisions can occur. Default: `undefined`. ``` -------------------------------- ### Configure Test Environment Source: https://styled-components.com/docs/tooling Registers the snapshot serializer and matchers globally by configuring the test environment for Jest or Vitest. ```javascript module.exports = { setupFilesAfterEnv: ['jest-styled-components'], }; ``` ```typescript import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { setupFiles: ['jest-styled-components'], environment: 'jsdom', }, }); ``` -------------------------------- ### Replace withComponent with as prop Source: https://styled-components.com/docs/faqs Shows how to replace the deprecated withComponent API with the as prop, either at definition time using attrs or at runtime. ```javascript import styled from 'styled-components'; const Button = styled.button` background: blue; color: white; `; const ButtonLink = styled(Button).attrs({ as: 'a' })``;
); ``` -------------------------------- ### injectGlobal API (Deprecated) Source: https://styled-components.com/docs/api Explains the deprecated injectGlobal API used for writing global CSS, now replaced by createGlobalStyle. ```APIDOC ## injectGlobal API (Deprecated) ### Description The `injectGlobal` API was removed and replaced by `createGlobalStyle` in styled-components v4. It was a helper method to write global CSS directly to the stylesheet. ### Method `injectGlobal` (Deprecated) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { injectGlobal } from 'styled-components' injectGlobal` @font-face { font-family: "Operator Mono"; src: url("../fonts/Operator-Mono.ttf"); } body { margin: 0; } ` ``` ### Response #### Success Response (200) Adds styles to the stylesheet directly. Does not return a component. #### Response Example N/A ``` -------------------------------- ### Test Utilities Source: https://styled-components.com/docs/api Utilities for finding rendered styled component instances within the DOM. ```APIDOC ## find / findAll ### Description Convenience methods to locate styled component instances in the DOM for testing purposes. ### Methods - **find(root, component)**: Returns the first instance found. - **findAll(root, component)**: Returns a NodeList of all instances found. ### Example ```javascript import { find, findAll } from 'styled-components/test-utils'; const node = find(document.body, MyStyledComponent); const nodes = findAll(document.body, MyStyledComponent); ``` ``` -------------------------------- ### Styled-Components: Using '&' for Component Overrides Source: https://styled-components.com/docs/basics Demonstrates the use of the '&' ampersand in styled-components to apply broad overrides to component instances, including hover states, sibling selectors, and class-based targeting. ```javascript const Thing = styled.div.attrs((/* props */) => ({ tabIndex: 0 }))` color: blue; &:hover { color: red; // when hovered } & ~ & { background: tomato; // as a sibling of , but maybe not directly next to it } & + & { background: lime; // next to } &.something { background: orange; // tagged with an additional CSS class ".something" } .something-else & { border: 1px solid; // inside another element labeled ".something-else" } ` render( Hello world! How ya doing? The sun is shining...
Pretty nice day today.
Don't you think?
Splendid.
) ``` -------------------------------- ### Attaching Props with .attrs Constructor Source: https://styled-components.com/docs/basics Shows how to use the .attrs constructor to attach static or dynamic props to a component. This avoids unnecessary wrapper components and allows for prop-based styling. ```typescript const Input = styled.input.attrs<{ $size?: string; }>(props => ({ type: "text", $size: props.$size || "1em", }))` color: #BF4F74; font-size: 1em; border: 2px solid #BF4F74; border-radius: 3px; margin: ${props => props.$size}; padding: ${props => props.$size}; `; render(

); ``` -------------------------------- ### Configure package.json resolutions Source: https://styled-components.com/docs/basics Recommended configuration for yarn users to ensure a single version of styled-components is used throughout the project. ```json { "resolutions": { "styled-components": "^6" } } ``` -------------------------------- ### Configure Custom Module Name for Processor Source: https://styled-components.com/docs/tooling Demonstrates how to configure the processor to recognize tagged template literals from libraries other than styled-components by specifying a moduleName. ```javascript import cool from 'other-library'; const Button = cool.button` color: blue; `; ``` ```json { "processors": [ [ "stylelint-processor-styled-components", { "moduleName": "other-library" } ] ] } ``` -------------------------------- ### SWC Plugin Configuration Source: https://styled-components.com/docs/tooling Configuration options for the SWC styled-components plugin to handle minification, dead code elimination, and namespace scoping. ```APIDOC ## SWC Plugin Configuration ### Description Configure the @swc/plugin-styled-components to optimize CSS output and bundle size. ### Parameters #### Request Body - **minify** (boolean) - Optional - Enables/disables CSS minification. - **pure** (boolean) - Optional - Enables pure annotations for dead code elimination. - **transpileTemplateLiterals** (boolean) - Optional - Enables transpilation of tagged template literals. - **namespace** (string) - Optional - Adds a namespace to class names to avoid collisions. ### Request Example { "jsc": { "experimental": { "plugins": [ [ "@swc/plugin-styled-components", { "minify": true, "pure": true, "namespace": "my-app" } ] ] } } } ```