Updating styled components is usually as simple as npm install
. Only major versions have the potential to introduce breaking changes (noted in the following release notes).
yarn add styled-components@beta
stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLStyleSheetManager
disableVendorPrefixes
with enableVendorPrefixes
proptsx
<StyleSheetManager enableVendorPrefixes>
{/* your React tree and ThemeProvider goes here */}
</StyleSheetManager>
withComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.13...v6.0.0-beta.14
Full Changelog: https://github.com/styled-components/styled-components/compare/v5.3.8...v5.3.9
yarn add styled-components@beta
stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.11...v6.0.0-beta.12
yarn add styled-components@beta
React.ComponentProps<typeof MyStyledComponent>
supportstylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.11...v6.0.0-beta.12
fix(constants): rework process env guard
Full Changelog: https://github.com/styled-components/styled-components/compare/v5.3.7-fixed...v5.3.8
fix: (React Native) passing testID as attrs property by @ku8ar (see #3857)
fix: prevent crash when process.env is not defined by Suhas R (see #3957)
Add support for the translate
attribute as a valid prop by @ay4toh5i (see #3619)
remove Ukraine message; it's now out of date and the message has been received
yarn add styled-components@beta
props.theme
in interpolations when using attrs
stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.10...v6.0.0-beta.11
yarn add styled-components@beta
stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.9...v6.0.0-beta.10
yarn add styled-components@beta
<use>
to domElements by @shanpriyan in https://github.com/styled-components/styled-components/pull/3901stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.8...v6.0.0-beta.9
yarn add styled-components@beta
stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.7...v6.0.0-beta.8
yarn add styled-components@beta
withComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadstylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.6...v6.0.0-beta.7
yarn add styled-components@beta
@container
CSS support)stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.5...v6.0.0-beta.6
yarn add styled-components@beta
stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.4...v6.0.0-beta.5
yarn add styled-components@beta
stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.3...v6.0.0-beta.4
yarn add styled-components@beta
stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.2...v6.0.0-beta.3
$as
and $forwardedAs
will be removed in the next major version, use the unprefixed props insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v5.3.5...v5.3.6
yarn add styled-components@beta
shouldForwardProp
for more advanced scenariosweb | native
) in the genericstylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.1...v6.0.0-beta.2
yarn add styled-components@beta
stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-beta.0...v6.0.0-beta.1
yarn add styled-components@beta
git.io
within error message by @SukkaW in https://github.com/styled-components/styled-components/pull/3733stylis
v4 (if using stylis-plugin-rtl
you'll need to upgrade to the newer version)@types/styled-components
in the past, you'll want to remove it$as
and $forwardedAs
props (use as
or forwardedAs
)$
prefix) for stuff you don't want to be passed to child component / HTMLwithComponent
API (87f511a228e5b13b1ff70a416409e0705e5bf456); use "as" prop insteadFull Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-alpha.5...v6.0.0-beta.0
styled-components/macros
babel-plugin-styled-components
(required for macros)Updated sandbox for alpha: https://codesandbox.io/s/styled-components-v6-alpha-sandbox-05bod1?file=/src/App.tsx
Full Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-alpha.4...v6.0.0-alpha.5
CSSProp
(this is in definitely typed but wasn't exposed by us)Recommended styled-components.d.ts
setup for your project:
// create styled-components.d.ts in your project source
// if it isn't being picked up, check tsconfig compilerOptions.types
import type { CSSProp } from 'styled-components';
import Theme from './theme';
type ThemeType = typeof Theme;
declare module 'styled-components' {
export interface DefaultTheme extends ThemeType {}
}
declare module 'react' {
interface DOMAttributes<T> {
css?: CSSProp;
}
}
Full Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-alpha.2...v6.0.0-alpha.4
Added "types" package.json fields for TS type acquistion.
Full Changelog: https://github.com/styled-components/styled-components/compare/v6.0.0-alpha.1...v6.0.0-alpha.2
Fixed the TS declarations not getting emitted correctly by rollup.
Full Changelog: https://github.com/styled-components/styled-components/compare/.v6.0.0-alpha.0...v6.0.0-alpha.1
After an epic amount of refactoring, I'm pleased to announce the first alpha of styled-components v6!
Highlights:
Full Changelog: https://github.com/styled-components/styled-components/compare/v5.2.0...v6.0.0-alpha.0
Full Changelog: https://github.com/styled-components/styled-components/compare/v5.3.1...v5.3.3
Fix forced server-side mode not triggering global styles (See #3566)
Fix SSR collisions caused by insufficient hash inputs and reordering of groups on the client, which is a regression in v5.2.0 (See #3563)
Fix dynamic creation React warning for React v18, backported to v5 by @lynndylanhurley (See #3564)
Add missing typeof window check when checking for duplicate instances of styled-components (See #3553)
Prevent ServerStyleSheet from emitting empty style tags, which would cause issues in IE11 (See #3555)
Support css tagged templates inside style objects, by @roginfarrer and @dvingo (See #3469)
For React Native based components, pass testID
down to the native component if specified for an easier time testing. (see #3365)
Enable users of the babel macro to customize the styled-components import with importModuleName
(see #3422)
[fix] COMPLEX_SELECTOR_PREFIX.includes wasn't transpiled (see #3397)
Make sure StyleSheetManager
renders all styles in iframe / child windows (see #3159) thanks @eramdam!
Rework how components self-reference in extension scenarios (see #3236); should fix a bunch of subtle bugs around patterns like & + &
Fix keyframes
not receiving a modified stylis instance when using something like stylis-plugin-rtl
(see #3239)
Big performance gain for components using style objects (see #3239)
We no longer emit dynamic classNames for empty rulesets, so some className churn may occur in snapshots
Preallocate global style placement to ensure cGS is consistently inserted at the top of the stylesheet; note that this is done in runtime order so, if you have multiple cGS that have overlapping styles, ensure they're defined in code in the sequence you would want them injected (see #3239)
Add "engines" to package.json (currently set to Node 10, the oldest supported LTS distribution) (see #3201) thanks @MichaelDeBoey!
Finally, special thanks to @willheslam for testing and some last minute fixes on this release!
We are planning to release 5.2 on September 2/3, please help us test!
yarn add styled-components@test
Preallocate global style placement to ensure cGS is consistently inserted at the top of the stylesheet; note that this is done in runtime order so, if you have multiple cGS that have overlapping styles, ensure they're defined in code in the sequence you would want them injected (see #3239)
NOTE: This is a behavioral change and might require adjustment in your codebase if you have many createGlobalStyle
components in use. We do not think it will affect the majority of projects other than fix existing bugs.
createGlobalStyle
is now React.StrictMode
compliant
Make sure StyleSheetManager
renders all styles in iframe / child windows (see #3159) thanks @eramdam!
Rework how components self-reference in extension scenarios (see #3236); should fix a bunch of subtle bugs around patterns like & + &
Fix keyframes
not receiving a modified stylis instance when using something like stylis-plugin-rtl
(see #3239)
Big performance gain for components using style objects (see #3239)
We no longer emit dynamic classNames for empty rulesets, so some className churn may occur in snapshots
Add "engines" to package.json (currently set to Node 10, the oldest supported LTS distribution) (see #3201) thanks @MichaelDeBoey!
shouldForwardProp
API for native and primitive platforms, which was previously missing in [v5.1.0] (see #3093)
This has been released under a patch bump instead of a minor, since it's only been missing from Native-support.Add shouldForwardProp
API (almost the same as emotion's, just a slightly different usage pattern); https://github.com/styled-components/styled-components/pull/3006
Sometimes when composing multiple higher-order components together, it's possible to get into scenarios when multiple layers consume props by the same name. In the past we've introduced various workarounds for popular props like "as"
but this power-user API allows for more granular customization of what props are passed down to descendant component children when using the styled()
HOC wrapper.
When combined with other APIs like .attrs()
this becomes a very powerful constellation of abilities.
Here's how you use it:
const Comp = styled('div').withConfig({
shouldForwardProp: (prop, defaultValidatorFn) => !['filterThis'].includes(prop),
})`
color: red;
`;
render(<Comp filterThis="abc" passThru="def" />);
# Renders: <div className="[generated]" passThru="def"></div>
The second argument defaultValidatorFn
is what we use internally to validate props based on known HTML attributes. It's provided so you can filter exactly what props you don't wish to pass and then fall-back to the default filtering mechanism if desired.
Other methods on the styled
HOC like .attrs
can be chained after withConfig()
, and before opening your template literal:
const Comp = styled('div').withConfig({
shouldForwardProp: (prop, defaultValidatorFn) => !['filterThis'].includes(prop),
}).attrs({ className: 'foo' })`
color: red;
`;
render(<Comp filterThis="abc" passThru="def" />);
# Renders: <div className="[generated] foo" passThru="def"></div>
Thanks @stevesims and all that contributed!
Add "transient props" API; https://github.com/styled-components/styled-components/pull/3052
Think of transient props as a lightweight, but complementary API to shouldForwardProp
. Because styled-components allows any kind of prop to be used for styling (a trait shared by most CSS-in-JS libraries, but not the third party library ecosystem in general), adding a filter for every possible prop you might use can get cumbersome.
Transient props are a new pattern to pass props that are explicitly consumed only by styled components and are not meant to be passed down to deeper component layers. Here's how you use them:
const Comp = styled.div`
color: ${props => props.$fg || 'black'};
`;
render(<Comp $fg="red">I'm red!</Comp>);
Note the dollar sign ($
) prefix on the prop; this marks it as transient and styled-components knows not to add it to the rendered DOM element or pass it further down the component hierarchy.
Added useTheme hook to named exports for react native (#2982)
Performance enhancements
Added some helpful new dev-time warnings for antipatterns
@import
inside createGlobalStyle
and what to do instead (#2997)It's finally here!!! 🚀See the migrating to v5 FAQ page for easy upgrade instructions!
...and much more all, with no breaking changes!
NOTE: At this time we recommend not using @import
inside of createGlobalStyle
. We're working on better behavior for this functionality but it just doesn't really work at the moment and it's better if you just embed these imports in your HTML index file, etc.
StyleSheetManager
enhancements
<StyleSheetManager stylisPlugins={[]}>...</StyleSheetManager>
disableVendorPrefixes
removes autoprefixing if you don't need legacy browser support; <StyleSheetManager disableVendorPrefixes>...</StyleSheetManager>
disableCSSOMInjection
forces using the slower injection mode if other integrations in your runtime environment can't parse CSSOM-injected styles; <StyleSheetManager disableCSSOMInjection>...</StyleSheetManager>
Removed the "subfunction" attrs syntax that was deprecated in v4
styled.div.attrs({ role: p => p.onClick ? 'button' : '' })`
color: red;
`
becomes
styled.div.attrs(p => ({ role: p.onClick ? 'button' : '' }))`
color: red;
`
Update css-to-react-native to v3.0.0 (#2811); the one breaking change noted is that unitless line height is no longer allowed when setting font properties
disallow /ad/i in generated class names (#2837); this change primarily helps to avoid some overly aggressive ad blockers that will mangle generated classnames containing the substring "ad"
if you use styled-components from CDN, in v5 the "react-is" dependency was added (make sure you add this to your project)
This should be the last RC before general v5 release in a week or two!
NOTE: If you've been testing this stylisPlugins
functionality with the stylis-rtl
plugin, please switch from stylis-rtl
to stylis-plugin-rtl
.
Note: we've switched from canary
to v5
as the target branch for the new release. It's basically the same, but fixed up so it'll merge cleanly onto master.
Changes from rc.1:
Changes from rc.0:
mixin-deep
so it is transpiled consistently for IEWe're almost there! After several months of work (thank you beta testers!) this is the first v5 release candidate build.
Overall v5 changes:
Major performance and bundle size improvements over v4, see the announcement blog for more details!
StyleSheetManager
enhancements
<StyleSheetManager stylisPlugins={[]}>...</StyleSheetManager>
disableVendorPrefixes
removes autoprefixing if you don't need legacy browser support; <StyleSheetManager disableVendorPrefixes>...</StyleSheetManager>
disableCSSOMInjection
forces using the slower injection mode if other integrations in your runtime environment can't parse CSSOM-injected styles; <StyleSheetManager disableCSSOMInjection>...</StyleSheetManager>
Removed the "subfunction" attrs syntax that was deprecated in v4
styled.div.attrs({ role: p => p.onClick ? 'button' : '' })`
color: red;
`
becomes
styled.div.attrs(p => ({ role: p.onClick ? 'button' : '' }))`
color: red;
`
Changes since the last beta:
disallow /ad/i in generated class names (#2837); this change primarily helps to avoid some overly aggressive ad blockers that will mangle generated classnames containing the substring "ad"
Update css-to-react-native to v3.0.0 (#2811); the one breaking change noted is that unitless line height is no longer allowed when setting font properties
replace merge-anything with mixin-deep (#2838); saving bytes, this is used when merging defaultProps
for extended styled components
shard createGlobalStyle by runtime instance (#2824); cGS is implemented such that it's really meant to be used as a singleton, but it's not uncommon for people to have multiple instances of the same cGS component on the page at once. This change ensures that as instances and mounted and removed the existing global styles don't get removed as well
memoize theme (#2820); a minor performance tweak when ThemeProvider
is given a reference-equal theme prop
make ThemeProvider error straightforward (#2787); more obvious messaging that the theme
prop is required when using ThemeProvider
Fix styled-components
's react-native
import for React Native Web, by @fiberjw (see #2797)
Remove dev-time warning if referencing a theme prop without an outer ThemeProvider
, the check for it isn't smart enough to handle cases with "or" or ternary fallbacks and creates undesirable noise in various third party integrations
useTheme()
hook (https://github.com/styled-components/styled-components/pull/2765)This is the last minor release before v5, please start using the beta and give us feedback!
This is a minor release not a patch release due to this change: #2738. Apologies if this causes some code churn in your projects, it was a long-standing bug that needed fixing.
Fix to use ownerDocument
instead of global document
, by @yamachig (see #2721)
Backport fix for SSR classname mismatches in development mode for some environments like next.js (see #2701)
Fix attrs not properly taking precedence over props
Backport fix where classnames are composed in the wrong order if custom class names are passed in (see #2760)
Fix add check for style tag detached - sheet in the style tag is null in this case, by @newying61 (see #2707)
add lightweight dev warning when theme is consumed but not provided (#2655)
fix component selectors + css prop usage (#2656)
5.0.0-beta.7 was unpublished due to a build error
remove the concept of foldedComponentIds (#2652); fixes an issue where if a folded component itself is used later in the component tree than the folding result it could lead to specificity clashes
bump too many classes warning back up to 200 (7af8e12bc32e44ea977e3e9fa6d45b6fdfd3a4e2)
revise & simplify how we determine the theme, fix createGlobalStyle
HMR and behavior around defaultProps.theme (#2647)
switched from stylis to @emotion/stylis (#2640); mostly a bundle size win and a minor performance boost
removed "stylisOptions" prop from StyleSheetManager
, but reimplemented the ability to remove vendor prefixes as "disableVendorPrefixes"
disable ComponentStyle staticness in non-production modes (#2634); should help fix some cases where className mismatches happen in runtimes like next.js dev mode
lower the threshold for the "too many classes" warning to 50 (#2622); the previous limit was 200, probably much too high
Fix babel macro with updated babel-plugin-styled-components (https://github.com/styled-components/styled-components/pull/2635)
Fix backward-compat issue with a way of doing SSR in v4 (https://github.com/styled-components/styled-components/pull/2639)
We'll explore reintroducing it in v5 but better safe than sorry.
Make it possible to initialize SC_ATTR
and SC_DISABLE_SPEEDY
via REACT_APP_*
.env variables for easier integration with CRA applications (see #2501)
Fix components being folded inappropriately when an interim HOC is present (see #2586)
Fix theme
prop for styled native components, also fixes theme
in
defaultProps
for them (see #2576)
Add "forwardedAs" prop to allow deeply passing a different "as" prop value to underlying components
when using styled()
as a higher-order component (see #2580)
Implement defaultProps folding (see #2597)
Major thanks to our wonderful contributors!
Remove className usage checker dev utility due to excessive false-positive noise in certain runtime environments like next.js and the related warning suppression prop (see #2563).
Attach displayName to forwardRef function as described in React docs (see #2508).
Compatibility with react-native-web 0.11 (see #2453).
Add stack trace to .attrs warning (see #2486).
Fix functions as values for object literals. (see 2489)
Remove validation in Babel macro, by @mAAdhaTTah (see #2427)
Thanks to our amazing contributors for leading the charge on this big minor release! Awesome perf stuff in there and QOL changes in preparation for v5.
Reduced GC pressure when using component selector styles. (see #2424).
Add svg tag marker
to domElements.js (see #2389)
Make the GlobalStyleComponent
created by createGlobalStyle
call the base constructor with props
(see #2321).
Move to Mono repository structure with lerna @imbhargav5 (see #2326)
Expose StyleSheetContext
and StyleSheetConsumer
for you fancy babes doing wild stuff
Filter suppressClassNameWarning
to not to pass down to the wrapped components @taneba (see #2365)
Fix an edge case where React would break streaming inside <textarea>
elements, which have special child behavior and aren't a suitable place to inject a style tag (see #2413)
Under the hood code cleanup of the Babel macro, by @lucleray (see #2286)
Fix function-form attrs to receive the full execution context (including theme) (see #2210)
Adjust innerRef
deprecation warning to not be fired if wrapping a custom component, since that underlying component may not be on forwardRef yet and actually using the prop (see #2211)
Expose the ThemeConsumer
and ThemeContext
exports for the native and primitives entries (see #2217)
Remove createGlobalStyle
multimount warning; Concurrent and Strict modes intentionally render the same component multiple times, which causes this warning to be triggered always even when usage is correct in the application (see #2216)
Folded components are now targetable via component selector as in v3 if you used the old .extend
API (see #2239)
Don't treat uppercased strings as tag-like components and don't filter out props from them (see #2225)
Performance optimization for fully static (no function interpolation) styled-components by avoiding using ThemeConsumer
since it isn't necessary, by @mxstbr (see #2166)
Allow disabling "speedy" mode via global SC_DISABLE_SPEEDY
variable, by @devrelm (see #2185)
To make use of this, you can either set SC_DISABLE_SPEEDY
in your app's entry file or use something like webpack.DefinePlugin
to do it at build time:
webpack.DefinePlugin({
SC_DISABLE_SPEEDY: true,
});
Attrs can now be passed a function (see #2200); thanks @oliverlaz for providing an early PoC PR for this!
e.g.:
styled.div.attrs(props => ({ 'aria-title': props.title }))``;
Fix the warnTooManyClasses
dev helper not being totally dead code eliminated in production (see #2200)
Deprecate functions as object keys for object-form attrs (see #2200)
e.g.:
styled.div.attrs({ 'aria-title': props => props.title })``; // bad
styled.div.attrs(props => ({ 'aria-title': props.title }))``; // good
Support for this will be removed in styled-components v5. The primary impetus behind this change is to eliminate confusion around basic functions vs styled-components vs React components provided as values in the object-form attrs constructor, each of which has different handling behaviors. The single outer function to receive the props and then return a props object is conceptually simpler.
The standalone CDN build is now UMD-compliant and can be used with RequireJS, etc.
Add pixels to unitless numbers when object interpolation is used, by @Fer0x (see #2173)
Trying to interpolate a non-styled component into CSS is now a hard error, rather than a warning (see #2173)
Interpolating a styled component into a string now returns the static component selector (emotion cross-compat)
import styled from 'styled-components';
const Comp = styled.div`
color: red;
`;
`${Comp}`; // .sc-hash
Add suppressClassNameWarning
prop to disable warning when wrapping a React component with styled()
and the className
isn't used, by @Fer0x (see #2156)
Expose ThemeContext to enable static contextType support for React 16.6, by @imbhargav5 (see #2152)
Filter out invalid HTML attributes from attrs
, by @Fer0x (see #2133)
Add warning if an attrs
prop is a function that returns an element, by @timswalling (see #2162)
Add suppressMultiMountWarning prop to disable warning on multiple cgs mount, by @imbhargav5 (see #2107)
Fix self-reference replacement edge cases, by @probablyup (see #2109)
This is a rollup of the highlights of beta 0-11 for convenience. See the migration guide for easy updating steps and the beta announcement blog for our summary of v4's changes, thought process, etc.
Add babel macro for full-featured interop with create react app v2+, by @lucleray (see #2032)
Expose ThemeConsumer
component, context consumer render prop component from the React.createContext
API if people are interested in using it rather than / in addition to the withTheme
HOC, by @probablyup
Add createGlobalStyle
that returns a component which, when mounting, will apply global styles. This is a replacement for the injectGlobal
API. It can be updated, replaced, removed, etc like any normal component and the global scope will update accordingly, by @JamieDixon @marionebl, @yjimk, and @imbhargav5 (see #1416)
const GlobalStyles = createGlobalStyle`
html {
color: 'red';
}
`;
// then put it in your React tree somewhere:
// <GlobalStyles />
Added a first-class API for rendering polymorphism via "as" prop. In most cases, this new prop will replace your need to use the .withComponent
API. It allows you to control what underlying element or component is rendered at runtime, while not messing with the styles, by @probablyup (see #1962)
import { Link } from 'react-router'
const Component = styled.div`
color: red;
`
// Examples
<Component>Hello world!</Component>
<Component as="span">Hello world!</Component>
<Component as={Link} to="home">Hello world!</Component>
Fix how ampersand is handled in self-referential selector combinations, e.g. & + &
(see #2071)
Remove deprecated consolidateStreamedStyles
API, by @probablyup (see #1906)
Remove deprecated jsnext:main
entry point from package.json, by @probablyup (see #1907)
Remove deprecated .extend
API, by @probablyup (see #1908)
Migrate to new context API, by @alexandernanberg (see #1894)
Remove TS typings; they are now to be found in DefinitelyTyped, by @probablyup. See https://github.com/styled-components/styled-components/issues/1778 for more information.
Add new data-styled-version
attribute to generated <style>
tags to allow multiple versions of styled-components to function on the page at once without clobbering each other, by @probablyup
It's still highly recommended to use aliasing via your bundler to dedupe libraries like styled-components and react.
[Breaking change] Refactor keyframes
helper, by @fer0x (see #1930).
Keyframes is now implemented in a "lazy" manner: its styles will be injected with the render phase of components using them.
keyframes
no longer returns an animation name, instead it returns an object which has method .getName()
for the purpose of getting the animation name.
Migrate to use new React.forwardRef
API, by @probablyup; note that this removes the innerRef
API since it is no longer needed.
Implement styled()
wrapper folding. In a nutshell, when you nest styled wrappers (e.g. styled(styled.div)
) the components are now folded such that only one is mounted that contains the merged styles of its ancestors. This is conceptually equivalent to the removed "extend" functionality, but without many of the downsides -- and it's automatic, by @probablyup (see #1962)
Add warning when component is not a styled component and cannot be referred via component selector, by @egdbear (see #2070)
When using CRA v2, import styled components from styled-components/macro
instead to gain all the benefits of our babel plugin.
Add a warning when wrapping a React component with styled()
and the className
isn't used (meaning styling isn't applied), by @Fer0x (see #2073)
Tweak the styled components base component naming to look nicer in DevTools, by @probablyup (see #2012)
Beef up the error message that sometimes occurs when multiple versions of styled components are used together and the StyleSheet instance can't be found, by @probablyup (see #2012)
Add enzymeFind
test utility to easily grab instances of a styled-component from enyzme mounted testing scenarios, by @probablyup (see #2049)
import { mount } from 'enzyme';
import React from 'react';
import styled from 'styled-components';
import { enzymeFind } from 'styled-components/test-utils';
const Thing = styled.div`
color: red;
`;
const wrapper = mount(
<div>
<Thing isCool />
</div>
);
const thing = enzymeFind(wrapper, Thing);
// expect(thing.props()).toHaveProperty('isCool') etc
Inline and optimize the static hoisting functionality to avoid a bundler bug and shed a bit of package weight, by @probablyup (see #2021
Blog post ・ Migration instructions
npm install --save styled-components@beta
Add warning when component is not a styled component and cannot be referred via component selector, by @egdbear (see #2070)
Fix how ampersand is handled in self-referential selector combinations, e.g. & + &
(see #2071)
Add babel macro for full-featured interop with create react app v2+, by @lucleray (see #2032)
When using CRA v2, import styled components from styled-components/macro
instead to gain all the benefits of our babel plugin.
Add a warning when wrapping a React component with styled()
and the className
isn't used (meaning styling isn't applied), by @Fer0x (see #2073)
Blog post ・ Migration instructions
npm install --save styled-components@beta
Add support for as
to be used with attrs
for better polymorphism, by @imbhargav5 (see #2055)
Fix withTheme
HOC to use a theme defined in defaultProps
of the wrapped component, by @theboyWhoCriedWoolf (see #2033)
Add enzymeFind
test utility to easily grab instances of a styled-component from enyzme mounted testing scenarios, by @probablyup (see #2049)
import { mount } from 'enzyme';
import React from 'react';
import styled from 'styled-components';
import { enzymeFind } from 'styled-components/test-utils';
const Thing = styled.div`
color: red;
`;
const wrapper = mount(
<div>
<Thing isCool />
</div>
);
const thing = enzymeFind(wrapper, Thing);
// expect(thing.props()).toHaveProperty('isCool') etc
Blog post ・ Migration instructions
npm install --save styled-components@beta
keyframes
with createGlobalStyle
, by @probablyup (see #2029)Blog post ・ Migration instructions
npm install --save styled-components@beta
Blog post ・ Migration instructions
npm install --save styled-components@beta
Revise createGlobalStyle HMR back to the original PR code without using componentDidMount
, by @probablyup (see #2017)
Some light refactoring to further reduce object allocations, by @probablyup (see #2016)
injectGlobal
warning; it's not actionable since the replacement API is in v4 only, so why say anything?Blog post ・ Migration instructions
npm install --save styled-components@beta
Fix a bug introduced from some refactoring that went into beta.5 around usage of keyframes
with multiple interpolations, by @probablyup (see #2013)
Tweak the styled components base component naming to look nicer in DevTools, by @probablyup (see #2012)
Beef up the error message that sometimes occurs when multiple versions of styled components are used together and the StyleSheet instance can't be found, by @probablyup (see #2012)
Add warning for the upcoming removal of the injectGlobal
API in v4.0, by @rainboxx (see #1867)
Backport from v4: Beef up the error message that sometimes occurs when multiple versions of styled components are used together and the StyleSheet instance can't be found, by @probablyup (see #2012)
Blog post ・ Migration instructions
npm install --save styled-components@beta
Fix issue with createGlobalStyle
and hot module reload, by @probablyup (see #2007)
Remove keyframes factory function, by @probablyup (see #2006)
Blog post ・ Migration instructions
npm install --save styled-components@beta
Note: this beta has a lot of internal changes. If you notice anything funky, please let us know. All tests are passing, etc.
Use PureComponent instead of Component for the StyledComponent base class, by @probablyup
Internal refactoring to simplify the codebase and make it more readily DCE-able, by @probablyup
Blog post ・ Migration instructions
npm install --save styled-components@beta
Fix an issue when streaming with very large amounts of output where sometimes styles might not make it to the client, by @probablyup (see #1996)
Fix the createGlobalStyle
multiusage warning having false positives, by @probablyup (see #1993)
Blog post ・ Migration instructions
npm install --save styled-components@beta
Expose ThemeConsumer
component, the "consumer" render prop component from the React.createContext
API if people are interested in using it rather than / in addition to the withTheme
HOC, @probablyup
Remove "no tags" experiment, by @probablyup (see #1987); if you are using the babel plugin, please make sure it's fully updated
Fixed an issue with createGlobalStyle
when the component was composed in multiple places and render of the subsequent component instance happened before unmount of the original; previously we removed styles immediately upon unmount of any instance without checking how many copies were still alive, by @probablyup (see #1989)
Blog post ・ Migration instructions
npm install --save styled-components@beta
Fixed an issue where createGlobalStyle
was clobbering the very next style to be applied during rehydration in production mode, by @probablyup (see #1976)
Removed some unused code, by @probablyup (see #1976)
Switched createGlobalStyle
to be a PureComponent
, by @probablyup (see #1976)
The first beta of v4 is here! 👏🥂
Blog post ・ Migration instructions
npm install --save styled-components@beta
There's a ton of new and exciting things in v4, along with breaking changes. See the full list below:
Remove deprecated consolidateStreamedStyles
API, by @probablyup (see #1906)
Remove deprecated jsnext:main
entry point from package.json, by @probablyup (see #1907)
Remove deprecated .extend
API, by @probablyup (see #1908)
Migrate to new context API, by @alexandernanberg (see #1894)
Remove TS typings; they are now to be found in DefinitelyTyped, by @probablyup. See https://github.com/styled-components/styled-components/issues/1778 for more information.
Add new data-styled-version
attribute to generated <style>
tags to allow multiple versions of styled-components to function on the page at once without clobbering each other, by @probablyup
It's still highly recommended to use aliasing via your bundler to dedupe libraries like styled-components and react.
[Breaking change] Refactor keyframes
helper, by @fer0x (see #1930).
Keyframes is now implemented in a "lazy" manner: its styles will be injected with the render phase of components using them.
keyframes
no longer returns an animation name, instead it returns an object which has method .getName()
for the purpose of getting the animation name.
Add createGlobalStyle
that returns a component which, when mounting, will apply global styles. This is a replacement for the injectGlobal
API. It can be updated, replaced, removed, etc like any normal component and the global scope will update accordingly, by @JamieDixon @marionebl, @yjimk, and @imbhargav5 (see #1416)
const GlobalStyles = createGlobalStyle`
html {
color: 'red';
}
`
// then put it in your React tree somewhere:
// <GlobalStyles />
Migrate to use new React.forwardRef
API, by @probablyup; note that this removes the innerRef
API since it is no longer needed.
Implement styled()
wrapper folding. In a nutshell, when you nest styled wrappers (e.g. styled(styled.div)
) the components are now folded such that only one is mounted that contains the merged styles of its ancestors. This is conceptually equivalent to the removed "extend" functionality, but without many of the downsides -- and it's automatic, by @probablyup (see #1962)
Added a first-class API for rendering polymorphism via "as" prop. In most cases, this new prop will replace your need to use the .withComponent
API. It allows you to control what underlying element or component is rendered at runtime, while not messing with the styles, by @probablyup (see #1962)
import { Link } from 'react-router'
const Component = styled.div`
color: red;
`
// Examples
<Component>Hello world!</Component>
<Component as="span">Hello world!</Component>
<Component as={Link} to="home">Hello world!</Component>
A note for preact
users: if you are doing the preact-compat
aliasing, it won't work with this beta because they haven't implemented React.createContext
in preact-compat
yet.
console.error
, now console.warn
), by @probablyupAdd warning for the upcoming removal of the extend
API in v4.0, by @probablyup (see #1909)
Throw Error if a React component was mistakenly interpolated within styles, by @imbhargav5 (see #1883)
Fix the primitives build, by @probablyup (see 24f097)
Fixed a bug in typings where isStyledComponent
was defined using an undefined variable, by @MayhemYDG (see #1876)
Add error system, by @probablyup (see #1881)
Fix "stream" module not being properly eliminated by rollup, by @probablyup
Add first-class support for functions that return objects, by @acjay (see #1820)
const Comp = styled.div((({ color }) => ({
color,
}))
Add support for the prop variants used by Preact (autofocus
, class
, for
), by @probablyup (see #1823)
Various performance improvements, by @probablyup (see #1843)
[TS] Revert #1798, by @Igorbek (see #1840)
[Internal] Add benchmarking suite, by @mxstbr (see #1833)
Fixed a regression when extending a styled(StyledComponent)
introduced in 3.3.0, by @probablyup (see #1819)
Adjust how displayName is generated when not using Babel to properly preserve a displayName passed via withConfig
, by @probablyup (see #1755)
[TS] Fix props being removed when indexed types are passed to WithOptionalTheme, by @devrelm (see #1806)
[TS] Allow TypeScript 2.9.1 to accept tagged template type argument, by @Igorbek (see #1798)
Add ref documentation for React.createRef(), by @julmot (see #1792)
Lots of 🔥fixes in this release! As always, thank you contributors for your hard work 🙇
Allow non-plain objects as ThemeProvider
themes, by @phyllisstein (see #1780)
[internal] Upgrade flow-bin to latest, by @halvves (see #1748)
[internal] Update various CI bits, by @probablyup (see #1769)
Reimplement SSR stream handling as a transform stream rather than a second-order readable stream, by @probablyup (see #1768)
Allow React Component as attr, by @valerybugakov (see #1751)
Added pointer events to valid attributes check, by @plankguy (see #1790)
Note: v3.3.1 was skipped due to a bad deploy.
The team is very excited to release v3.3.0, containing a number of important bugfixes and quality of life improvements to the library! This will probably be the last feature release before v4.0 (roadmap) this summer.
Thank you so much to all the people who contributed. styled-components is nothing without its community ❤️
Fix off-by-one error in insertRuleHelpers.js, by @migueloller (see #1749)
Add first-class support for objects, by @mxstbr (see #1732)
const Component = styled.div({
color: 'blue'
})
Fix typo in console warning about multiple instances, by @lucianbuzzo (see #1730)
Make the multiple instance warning criteria a little more strict to avoid badgering people running unit tests, by @probablyup (see #1693)
Fix React.createRef()
values for innerRef
being ignored in React Native, by @simonbuchan (see #1718)
Hoist non-react static properties on wrapped classes, by @probablyup (see #1750)
Support attributes prefixed by x-
, by @mlecoq (see #1753)
The primary fix in this patch release was related to a misconfiguration in the stylis rule splitter which could cause some rules to be discarded when there was no whitespace around selector operands.
Make sure that you're installing v3.2.5
as v3.2.4
was missing some postinstall scripts for our OpenCollective message 😅
The preprocess
option was never here to stay and its experiment has essentially proven to be insufficient for our future goals. Check out Sweetsour/ISTF for our current effort of making styled-components more performant and adding a CSS pipeline to it: https://github.com/kitten/sweetsour
Thanks to @Samatar26 for his PR!
process.env.SC_ATTR
to override our style tag's marker attributeWhile we're figuring out how to improve our context-drive StyleSheetManager in a stable way that works with SSR and sharded stylesheets, we would still like to provide a way for you to use styled-components that enables widgets and other use-cases where it might be necessary to prevent us from destroying your stylesheet on pages.
Specifically this affects people who are building non-SSR code that runs on pages where styled-components is already in place. In these cases our SSR rehydration would go along and happily remove another module's style tags. We haven't considered this closely as it is not a good practice in our eyes to run duplicated styled-components modules in a single app. But when you're not dealing with a single app only it might make sense.
You can now change the the style tag's styled-components attribute by bundling with the SC_ATTR
environment variable. Given a setup where you can set this variable, we will now inject style tags with a different attribute, so that they're not affected by the standard SSR rehydration.
Documentation will follow soon; Thanks to @Fer0x for this change!
This release simply frees up some memory by removing cloned StyleSheet
s when they're not needed anymore.
If you've noticed that v3.2 would cause your server-side rendered app to output all styles it knows of, you weren't alone!
The ServerTag
was accidentally cloning itself incorrectly. This meant that the ServerStyleSheet
would inherit the same server styles from the “master” StyleSheet.
We now clone the tag correctly and a test is in place to ensure this doesn't happen again, since this bug came up a couple of times in past v2 releases. Thanks to @DeividasK for reporting this bug!
Have some styles gone missing? In the newer >=3.1
versions that introduced speedy mode (i.e. insertRule
support) some rules might not have been injected properly. This came down to insertRule
being more strict with what we add. In development an incorrectly formatted CSS rule might not cause much trouble, but in production insertRule
complains about it.
Stylis
, more specifically stylis-rule-sheet
, was generating invalid CSS when at-rules were nested inside style rules. For instance the following CSS would cause trouble:
/* input */
&:hover {
@media (min-width: 768px) { color: papayahwip; }
}
/* incorrect output */
@media (min-width: 768px) {
&:hover { color: papayahwip; }
}}
/* ^ note the extra closing curly brace */
/* v3.2.2 fixed output */
@media (min-width: 768px) {
&:hover { color: papayahwip; }
}
IS_BROWSER
detectionBefore v3.2.2
we would check whether styled-components is running inside the browser using: typeof window !== 'undefined'
. This proofed insufficient in a couple of special cases for some people, so we have now added 'HTMLElement' in window
to this check.
Thanks to @danieldunderfelt for contributing this fix!
We accidentally removed dangerouslySetInnerHtml
in our SSR output with just some children string. This would cause some characters to be encoded.
We have corrected this mistake and more unit tests are now in place to prevent this from happening again. Thanks to @misund for reporting this mistake!
@import
at-rules@import
rules must appear at the top of style sheets (i.e tags).
In older versions we used to shard our style tags into local and global ones. Because any CSS that is being passed to us is also reordered, so that @import
rules appear at the top, often this would mean that a lone injectGlobal
would get away with @import
rules.
This wasn't sufficient as using @import
in a component (obviously unsupported and not recommended) or in another consecutive injectGlobal
would cause this logic to break, since @import
wouldn't appear at the top of the stylesheet anymore.
This oversight was made worse by the fact that we stopped sharding local and global style tags. This would mean that @import
could now show up fairly late in a stylesheet, instead of at its top.
In this version we introduce a patch that creates an additional style tag at the top of all other ones that we create, when necessary, which is going to accept all @import
rules separately. So when you use injectGlobal
and pass it an @import
rule, it will now be stripped out of the rest of your CSS, and put into a completely isolated style tag.
This is a small minor release that introduces a couple of minor changes, but also a complete rewrite of our StyleSheet implementation. Not only is it smaller, but it also lowers the barrier to entry for new contributors (like yourself, dear reader, hopefully!) to read and understand it, and eventually contribute great new features!
consolidateStreamedStyles
If you’ve recently migrated to streamed server-side-rendered styles, then you will be familiar with our consolidateStreamedStyles
function, which was an “extended rehydration” that moved all streamed styled-components style tags when called.
Due to our refactor of our StyleSheet behaviour (see below), our new rehydration implementation now takes care of this for you automatically.
This function will now output a deprecation warning when it’s being used and effectively does nothing at all. (Take a look at its source for more information)
StyleSheet
and ServerStyleSheet
We now handle the style rules around a “style tag” based approach, which also means that our BrowserStyleSheet
is a thing of the past. Depending on the environment, we will now switch between server, browser, and insertRule style tags, which all abstract their internal behaviour.
The concept of “local” vs “global” styles has been removed, in anticipation of some upcoming, future APIs, and our rehydration has been rewritten as well. You will see only a single style tag after rehydration, and now splits between style tags when injecting global styles as well. This is not a breaking change, but produces the same behaviour and specificity as it did before. (Change)
You will also notice a couple of improved and more detailed error messages—if you ever run into them that is—which will help you to understand some things that might go wrong more easily. (Change)
Style tags will now also be injected consecutively in the DOM. This means that styled-components won’t append them to the target, but will append them to its last style tag, if a first one was already injected. This should help you to predict the order of injection, when dealing with external CSS. (Change)
You can now pass an element to a StyleSheetManager
and all the components in its context below in the tree will add their styles to new tags in the specified target.
While this is not guaranteed to work with SSR yet, it can help you to easily add runtime-styles to a different part of the DOM. For example the shadow DOM.
Starting from this version, style-components will log a warning when multiple instances of it are being bundled and run on the same page. Due to our rehydration this can lead to errors, where one instance of styled-components will interfere with the other. This is why we have decided to add a small warning notifying you of this, since we don’t see the practice of adding multiple styled-components instances to a single page as a best practice.
Please note that this warning won’t show up, when older version of styled-components are present, as they don’t contain the code necessary to be detected.
StyleSheet.remove
API (Internal)This is an internal API that allows us to remove rules and components from our StyleSheets, which will come in handy for some new APIs for global styles quite soon.
We accidentally disabled semicolon autocompletion in stylis, which accidentally introduced an unnoticed breaking change in a past version a while back.
Semicolon autocompletion is now enabled and back again. Thanks to @Blasz for reporting this mistake!
insertRule
aka production modeOur version of stylis-rule-sheet was updated which fixes nested media queries which can now be used as is expected in production. (see #1529 and #1528)
type="text/css"
-attribute from style tag to remove warnings from w3c validator (see #1551)Thanks to the numerous contributors and maintainers who have worked towards this release. We're sorry if some names are missing, so thanks additionally goes out to everyone who’s worked hard to get v3 out!
(In no particular order)