styled-components is a CSS-in-JS library that enables styling React components using tagged template literals. It removes the mapping between components and styles, supports dynamic styling based on props, and provides comprehensive theming support with server-side rendering capabilities.
npm install styled-componentsimport styled, { css, keyframes, createGlobalStyle, ThemeProvider } from "styled-components";For CommonJS:
const styled = require("styled-components").default;
const { css, keyframes, createGlobalStyle, ThemeProvider } = require("styled-components");For React Native:
import styled from "styled-components/native";import styled from "styled-components";
// Create a styled component
const Button = styled.button`
background-color: #007bff;
border: none;
border-radius: 4px;
color: white;
cursor: pointer;
font-size: 16px;
padding: 10px 20px;
&:hover {
background-color: #0056b3;
}
`;
// Use dynamic styling with props
const StyledButton = styled.button<{ primary?: boolean }>`
background-color: ${props => props.primary ? '#007bff' : '#6c757d'};
color: white;
padding: 10px 20px;
`;
// Usage in React
function App() {
return (
<div>
<Button>Regular Button</Button>
<StyledButton primary>Primary Button</StyledButton>
</div>
);
}styled-components is built around several key concepts:
Primary API for creating styled components using template literals. Supports all HTML elements and custom components with full TypeScript integration.
declare const styled: Styled;
interface Styled {
<Target extends WebTarget>(target: Target): StyledInstance<'web', Target, React.ComponentPropsWithRef<Target>>;
// HTML element shortcuts
div: StyledInstance<'web', 'div', React.HTMLAttributes<HTMLDivElement>>;
span: StyledInstance<'web', 'span', React.HTMLAttributes<HTMLSpanElement>>;
button: StyledInstance<'web', 'button', React.ButtonHTMLAttributes<HTMLButtonElement>>;
input: StyledInstance<'web', 'input', React.InputHTMLAttributes<HTMLInputElement>>;
// ... all other HTML elements
}Helper functions for CSS composition, animations, and global styles. Essential for advanced styling patterns and reusable style definitions.
function css<Props extends object>(
strings: TemplateStringsArray | StyleFunction<Props> | StyledObject<Props>,
...interpolations: Interpolation<Props>[]
): RuleSet<Props>;
function keyframes(
strings: TemplateStringsArray,
...interpolations: Interpolation<any>[]
): Keyframes;
function createGlobalStyle<Props extends object>(
strings: TemplateStringsArray,
...interpolations: Interpolation<Props>[]
): React.ComponentType<ExecutionProps & Props>;Comprehensive theming support with React Context integration. Provides theme providers, consumers, and utilities for consistent design systems.
declare const ThemeProvider: React.ComponentType<{
theme: DefaultTheme | ((outerTheme?: DefaultTheme) => DefaultTheme);
children?: React.ReactNode;
}>;
declare const ThemeContext: React.Context<DefaultTheme | undefined>;
declare const ThemeConsumer: React.Consumer<DefaultTheme | undefined>;
function useTheme(): DefaultTheme; // Throws error if no ThemeProvider
function withTheme<Props>(Component: React.ComponentType<Props>): React.ComponentType<Props>;Complete SSR support with style extraction, hydration, and server-side style sheet management. Critical for production applications and SEO.
class ServerStyleSheet {
collectStyles(tree: React.ReactElement): React.ReactElement;
getStyleTags(): string;
getStyleElement(): React.ReactElement[];
seal(): void;
instance: StyleSheet;
}
declare const StyleSheetManager: React.ComponentType<{
sheet?: StyleSheet;
target?: HTMLElement;
children?: React.ReactNode;
}>;Full React Native integration with platform-specific optimizations and native component support.
// From 'styled-components/native'
declare const styled: {
<Target extends React.ComponentType<any>>(target: Target): NativeStyledInstance<Target>;
ActivityIndicator: NativeStyledInstance<typeof ActivityIndicator>;
Button: NativeStyledInstance<typeof Button>;
FlatList: NativeStyledInstance<typeof FlatList>;
Image: NativeStyledInstance<typeof Image>;
ScrollView: NativeStyledInstance<typeof ScrollView>;
Text: NativeStyledInstance<typeof Text>;
TextInput: NativeStyledInstance<typeof TextInput>;
TouchableOpacity: NativeStyledInstance<typeof TouchableOpacity>;
View: NativeStyledInstance<typeof View>;
// ... other React Native components
};Complete TypeScript support with advanced type definitions, generic type preservation, and theme typing.
interface DefaultTheme {}
interface IStyledComponent<Target, Props> extends React.ComponentType<Props> {
styledComponentId: string;
withComponent<NewTarget>(tag: NewTarget): IStyledComponent<NewTarget, Props>;
}
type Interpolation<Props> =
| string
| number
| false
| undefined
| null
| StyleFunction<Props>
| StyledObject<Props>
| TemplateStringsArray
| Keyframes
| RuleSet<Props>
| Interpolation<Props>[];function isStyledComponent(target: any): target is IStyledComponent<any, any>;declare const version: string;For testing and debugging styled components.
Warning: These are internal APIs that should only be used for advanced debugging and development tools. They may change without notice.
interface __PRIVATE__ {
StyleSheet: typeof StyleSheet;
mainSheet: StyleSheet;
}
declare const __PRIVATE__: __PRIVATE__;// Target types
type WebTarget = string | React.ComponentType<any>;
type NativeTarget = React.ComponentType<any>;
// Styled component instance interface
interface StyledInstance<Runtime, Target, Props> {
(strings: TemplateStringsArray, ...interpolations: Interpolation<Props>[]): IStyledComponent<Target, Props>;
attrs<AttrsProps>(attrs: Attrs<AttrsProps & Props>): StyledInstance<Runtime, Target, Props & AttrsProps>;
withConfig(config: StyledOptions<Runtime, Props>): StyledInstance<Runtime, Target, Props>;
}
// Execution context types
interface ExecutionProps {
as?: React.ElementType;
forwardedAs?: React.ElementType;
theme?: DefaultTheme;
}
interface ExecutionContext extends ExecutionProps {
theme: DefaultTheme;
}
type StyleFunction<Props extends object> = (
executionContext: ExecutionContext & Props
) => Interpolation<Props>;
interface StyledObject<Props extends object> {
[key: string]:
| string
| number
| StyleFunction<Props>
| StyledObject<Props>
| undefined;
}
type RuleSet<Props extends object = {}> = Interpolation<Props>[];
interface Keyframes {
id: string;
name: string;
rules: string;
}interface StyledOptions<Runtime extends 'web' | 'native', Props extends object> {
attrs?: Attrs<Props>[] | undefined;
componentId?: (Runtime extends 'web' ? string : never) | undefined;
displayName?: string | undefined;
parentComponentId?: (Runtime extends 'web' ? string : never) | undefined;
shouldForwardProp?: ShouldForwardProp<Runtime> | undefined;
}
type Attrs<Props extends object> =
| Partial<Props>
| ((props: ExecutionContext & Props) => Partial<Props>);
type ShouldForwardProp<Runtime> = (
prop: string,
elementToBeCreated: Runtime extends 'web' ? WebTarget : NativeTarget
) => boolean;
type StyledTarget<Runtime> = Runtime extends 'web' ? WebTarget : NativeTarget;// Fast omit utility for better TypeScript performance
type FastOmit<T extends object, U extends string | number | symbol> = {
[K in keyof T as K extends U ? never : K]: T[K];
};
// Type inference utility
type NoInfer<T> = [T][T extends any ? 0 : never];
// Omit never values from object types
type OmitNever<T> = { [K in keyof T as T[K] extends never ? never : K]: T[K] };
// Base object type
type BaseObject = {};
// Runtime type for distinguishing web vs native
type Runtime = 'web' | 'native';
// Styled component brand for type checking
type StyledComponentBrand = { readonly _sc: symbol };// Advanced component props for polymorphic "as" prop support
type PolymorphicComponentProps<
Runtime extends 'web' | 'native',
BaseProps extends object,
AsTarget extends StyledTarget<Runtime> | void,
ForwardedAsTarget extends StyledTarget<Runtime> | void
> = FastOmit<BaseProps, keyof ExecutionProps> &
FastOmit<ExecutionProps, 'as' | 'forwardedAs'> & {
as?: AsTarget;
forwardedAs?: ForwardedAsTarget;
};
// Polymorphic component interface supporting dynamic "as" prop
interface PolymorphicComponent<Runtime extends 'web' | 'native', BaseProps extends object>
extends React.ForwardRefExoticComponent<BaseProps> {
<
AsTarget extends StyledTarget<Runtime> | void = void,
ForwardedAsTarget extends StyledTarget<Runtime> | void = void,
>(
props: PolymorphicComponentProps<Runtime, BaseProps, AsTarget, ForwardedAsTarget>
): React.JSX.Element;
}