Looking for v5?
The main
branch is under development of the upcoming v6 major version of styled-components. For changes targeting v5, please point your PRs at the legacy-v5
branch.
Utilising tagged template literals (a recent addition to JavaScript) and the power of CSS, styled-components
allows you to write actual CSS code to style your components. It also removes the mapping between components and styles β using components as a low-level styling construct could not be easier!
const Button = styled.button`
color: grey;
`;
Alternatively, you may use style objects. This allows for easy porting of CSS from inline styles, while still supporting the more advanced styled-components capabilities like component selectors and media queries.
const Button = styled.button({
color: 'grey',
});
Equivalent to:
const Button = styled.button`
color: grey;
`;
styled-components
is compatible with both React (for web) and React Native β meaning it's the perfect choice even for truly universal apps! See the documentation about React Native for more information.
Supported by Front End Center. Thank you for making this possible!
Upgrading from v4
npm install styled-components@^5.0.0 react@^16.8 react-dom@^16.8 react-is@^16.8
- ??
- Profit!
If you use jest-styled-components, make sure you update that too.
Docs
See the documentation at styled-components.com/docs for more information about using styled-components
!
Quicklinks to some of the most-visited pages:
Example
import React from 'react';
import styled from 'styled-components';
// Create a <Title> react component that renders an <h1> which is
// centered, palevioletred and sized at 1.5em
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// Create a <Wrapper> react component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
// Use them like any other React component β except they're styled!
<Wrapper>
<Title>Hello World, this is my first styled component!</Title>
</Wrapper>
This is what you'll see in your browser:
Babel Macro
If you're using tooling that has babel-plugin-macros set up, you can switch to the styled-components/macro
import path instead to gain the effects of the babel plugin without further setup.
import styled from 'styled-components/macro';
// A static className will be generated for Title (important for SSR)
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
If you wish to provide configuration options to the babel plugin similar to how you would in a .babelrc
, see this guide. The config name is "styledComponents"
.
styled-components
Built with A lot of hard work goes into community libraries, projects, and guides. A lot of them make it easier to get started or help you with your next project! Thereβs also a whole lot of interesting apps and sites that people have built using styled-components.
Make sure to head over to awesome-styled-components to see them all! And please contribute and add your own work to the list so others can find it.
Contributing
If you want to contribute to styled-components
please see our contributing and community guidelines, they'll help you get set up locally and explain the whole process.
Please also note that all repositories under the styled-components
organization follow our Code of Conduct, make sure to review and follow it.
Badge
Let everyone know you're using styled-components β
[](https://github.com/styled-components/styled-components)
Contributors
This project exists thanks to all the people who contribute. [Contribute].
Backers
Thank you to all our backers!
Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
License
Licensed under the MIT License, Copyright Β© 2016-present Glen Maddern and Maximilian Stoiber.
See LICENSE for more information.
Acknowledgements
This project builds on a long line of earlier work by clever folks all around the world. We'd like to thank Charlie Somerville, Nik Graf, Sunil Pai, Michael Chan, Andrey Popp, Jed Watson & Andrey Sitnik who contributed ideas, code or inspiration.
Special thanks to @okonet for the fantastic logo.
Separate HTML attributes from styling props
Background
I am trying to style a 3rd party "masked" input. The styles are applied correctly, however, there are props I pass into the "styled" element that are used within the CSS logic of the styled component that I don't want passed down to the 3rd party input. This logs an error saying there are undesired props being put on the input (this is also an issue with the 3rd party component that isn't properly stripping out what should go on the input).
I could see it being an enhancement where we specify what props to terminate at the "styled" part. However, this also could just be looked at as the 3rd party component having an issue not removing those props. I'm fine with it being an issue with the 3rd party developer but just wanted to mention the issue and see if this is happening to other people and if it is worth it to build some extra logic in.
Screenshot
v4 beta constructive feedback
Please provide as much detail as possible when commenting here so we can help! A huge amount of time and thought has been put into the API changes. We know it won't be a "flip a switch" situation, but the ergonomics of the library going forward should be markedly better and more flexible.
Discuss SSR API and methods
I just want to kick off a discussion to finalise our SSR API.
So API came from the comments on the #214
Please feel free to suggest what the API will look like, (let the bikeshedding begin!)
Also if we're already doing de-duping in SSR level, do we even need reset()? (related issue #378) Or would that just be a convenience function since we don't need it anymore?
cc @mxstbr / @geelen
How do I provide props to styled elements in Typescript?
I looked at the docs and other than creating a whole empty component purely for providing a definition of props I'm not sure of if it's possible to provide custom props to a styled element other than theme.
Example
For the above example I don't know how to make it not error.
Use insertRule in browser
Premlinary patch for using
insertRule
api. Seems to help performance quite a bit, but the implementation is kind of hacky. I'm just using a naive regexp to split up rules but I'm looking to use a stylis middleware (@mxstbr has suggested looking into https://github.com/thysultan/stylis.js/issues/59 and https://github.com/threepointone/glam/issues/5 for reference)Edit by @philpl: Updated to respect and enforce component order (out of order injection) and to rehydrate into a new SpeedyBrowserTag purely using
insertRule
. This also removes a couple of APIs from the BrowserTags that are not needed in production.Deprecate .extend in favour of only styled(Component)
The FAQ explains the difference between
styled()
and.extend
. However I wonder if it would be possible to take the decision out of the devs hand and havestyled
check for the handed in Component if its already a styled component. If it is.extend
it otherwise create a new class.Was this considered at one point?
5.0 Roadmap
Test it out:
5.0 milestone
5.1 candidate
didn't do
follow along on the ~canary~ v5 branch
evolving
v2 prerelease feedback
If you're using the v2 pre-release, please let us know in a comment below if it works well for you! If you encounter bugs, please submit individual issues for them!
Babel transform
~~We need a way (probably babel transform?) to extract and precompile the static styles of our components!~~
Extracting static styles is actually not what we want, we want to pre-parse the CSS in a build step but leave it in the JS: See this comment
Has anybody done this before? I know I haven'tβ¦
SSR Memory Leak with v5 release candidate 2
Environment
Default, Baseline
After upgrade to RC 2
Notes: Both environments use TypeScript, Next.JS and latest versions of react
Steps to Reproduce
_document.js
file found in thewith-styled-components
example of next.js.npx loadtest -c 5 --rps 10 -k -t 90 http://localhost:8080/
Memory Timeline In N|Solid on version 4.4.1
heapsnapshot
Memory Timeline in N|Solid on Version 5 RC 2
heapsnapshot
Comparison of Heap snapshots
RC 2 is on the left. The snapshots were taken as close to the same point as possible (immediately following the load test that was run with the same stats: 5 concurrent threads, keep-alive connections, 10 requests per second for 90 seconds). The only change between the two is upgraded to RC 2.
Server Side Rendering: First paint missing some styles (FOUC)
Environment
System:
Binaries:
npmPackages:
Reproduction
The chunk of server side rendering code used:
My index template (index.ejs) as such:
And just in case some styled-component code, though I don't expect this to be the issue (possibly because of using
extend
?).Steps to reproduce
Expected Behavior
For all styles to be applied during first paint (like so below).
Actual Behavior
Only some styles being applied on first paint, while some rules (specifically
font-size
) seems to be applied only after the JS bundle is parsed and executed.Remarks
As you can see in the two screenshots, I get a flash of content where the
font-size
rule isn't respected. I had this same issue withfont-family
actually, but dealt with it by putting it as an inline style on my<body>
tag. Possibly this is a Flash of Unstyled Text (FOUT), but I'm honestly quite lost as to why these specific rules are being ignored on the first paint.I state that the rules seem to be applied only after the main JS bundle is loaded/parsed/executed because of examining the request for
app.js
closely in the Chrome Network panel. Is this possible a webpack issue where I need to optimize the bundle further?global styles in next.js 13
I am using Next.js 13 and followed the official docs to introduce styled-components in my project https://beta.nextjs.org/docs/styling/css-in-js
this is what my layout.tsx looks like that lives in /app
Doing that I get this error:
when I remove or when I put above the error disappears but then I see the page without the style for a second and then the global styles kick in after
if I wrap everything inside
that is insidecustomSyntax for Stylelint v14+
Hi there π First of all, thanks again for all of your work maintaining Styled Components and the ecosystem, really amazing!
Given the bleak situation with Stylelint v14+ and Styled Components / Emotion (TLDR:
stylelint-processor-styled-components
is deprecated and archived,@stylelint/postcss-css-in-js
will probably be deprecated (second reference, third reference), it seems that one of the next releases will probably mean the end of working Stylelint tooling for Styled Components and Emotion.There's a lot of confusing information out there, but the best, least broken config for now is
processors: ['stylelint-processor-styled-components']
+customSyntax: 'postcss-scss'
.I would suggest the following things to avoid tooling breakages:
stylelint-processor-styled-components
repo - I'm not suggesting to provide any support for this - it can be maintained by selected community members, but @alexander-akait's issue about deprecating the package does not seem valid anymore, now that@stylelint/postcss-css-in-js
will be deprecatedcustomSyntax
should be developed for Stylelint v14+ (this is the main point of this issue) - this may be potentially based onpostcss-lit
, @43081j even started on acustomSyntax
for Styled Components herestylelint-processor-styled-components
repo once there is a stablecustomSyntax
option that is not@stylelint/postcss-css-in-js
cc @probablyup @alexandernanberg @SukkaW @mxstbr @agriffis (Styled Components maintainers) @emmatown @Andarist @srmagura (Emotion maintainers) @alexander-akait @ybiquitous @jeddy3 (Stylelint maintainers) @43081j (
postcss-lit
maintainer)Prior art:
Reproduction
https://github.com/styled-components/styled-components/issues/3607#issuecomment-1321151513
Steps to reproduce
Try to reliably set up Stylelint v14+ with Styled Components or Emotion
Expected Behavior
It works reliably and easily with a non-deprecated, non-archived package
Actual Behavior
It works partially with deprecated and/or archived packages (but will probably break in the future)
Upgrading react dependency to 18.1
Hi
Im currently getting a dependency conflict issue with styled components. there is a small work around however it cause other issues for other dependencies.
Is there way that the styled component repo can upgrade its react dependent to use react 18.1 and not 16.8?
Environment
System:
Binaries:
Reproduction
https://codesandbox.io/s/styled-components-base-gc367
Steps to reproduce
Expected Behavior
Install with no issues
Actual Behavior
dependancy issue with react, using '>=16.8.0' in styled components and 18.1.0 in personal repo
css animation doesn't work if use CSSOM API
Environment
System:
Binaries:
npmPackages:
Reproduction
I pushed my demo to https://github.com/dexbol/test-styled-components-v6-beta .
Steps to reproduce
Don't need
npm install
, just visit index.html by localhost or just file url. Change the global variableSC_DISABLE_SPEEDY
to false or true.Expected Behavior
The circle should be rotating regardless of the value of
SC_DISABLE_SPEEDY
.Actual Behavior
Rotating animation is not running if
SC_DISABLE_SPEEDY
is falseThere is no code prompt at all
There is no code prompt at all. The normal css files are. It is no good to import style components, and I have also installed the style components plug-in. My vscode
SSR / Styled Components SEO Issues?
First I wanted to say thanks for creating and managing this library, it's really nice!
Next, I wanted to see if anyone else had any issues with SEO from Styled Components while using SSR? About 9 months ago we completely lost all our SEO rankings (for daily content) and have been through everything trying to figure it out. We've optimized our site loading times and performance to the 90's in lighthouse but our pages would sometimes get picked up / indexed from google news and then dropped within 24 hours (the google second pass).
Then, on Wednesday, one of our devs pushed some code that broke SSR loading by accident and the next day we had dozens of page 1 rankings from the day's posts! As soon as we fixed the SSR break, we vanished from google once again. So we broke it again today and are now back on google.
We've narrowed the issue down to 2 potential culprits - Styled Components and Fresnel. Both of which might be contributing factors, here's why:
With SSR, styled components works like this: It puts all the CSS in the
<head>
of the site and on rehydrate, moves it into a separate .css file. This means google receives one set of raw HTML code and then when it renders, it sees something much smaller code wise. UI is the same still but code looks a lot different after it's rendered.With SSR Fresnel does the same thing. Sends all the HTML to google and when google renders the page (using mobile) and it rehydrates, all the desktop code is removed from the HTML.
With those factors, it's highly likely that google is seeing this variance in file size / code as potential cloaking because our pages would go from page 1-2 to 10+ where you can't find it in google w/out using a direct URL match. We never received a manual action or any note from google but it's clear we triggered an automated penalty.
A little extra context:
At midnight, dozens of pages are added to our sitemap and then submit to google. Within a few hours, the pages get listed in google. When using CSR, we are ranked the next day. When using SSR, we aren't even in the index with an exact match URL search until 1-2 days later, and if we are indexed, we aren't in the first 10 pages.
Has anyone that uses this combo experienced anything similar?