Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
styled-components
Advanced tools
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅
The styled-components npm package is a library for styling React applications. It utilizes tagged template literals to style your components. It allows you to write actual CSS code to style your components without worrying about class name bugs due to its unique feature of scoped styles. It also supports theming, dynamic styling, and can work with server-side rendering.
Basic Styling
This feature allows you to create React components with styles attached to them. The example shows how to create a styled button component.
import styled from 'styled-components';
const Button = styled.button`
background: palevioletred;
border-radius: 3px;
border: none;
color: white;
`;
Theming
Theming support allows you to define a set of constants for styling that can be accessed throughout your application. The example shows how to use a theme to style a button component.
import styled, { ThemeProvider } from 'styled-components';
const ThemeButton = styled.button`
background: ${props => props.theme.main};
color: ${props => props.theme.secondary};
`;
const theme = {
main: 'mediumseagreen',
secondary: 'white'
};
<ThemeProvider theme={theme}>
<ThemeButton>Click me</ThemeButton>
</ThemeProvider>;
Dynamic Styling
Dynamic styling allows you to pass props to your styled component to change its appearance dynamically. The example shows a div that changes its background and text color based on props.
import styled from 'styled-components';
const DynamicDiv = styled.div`
background: ${props => props.bgColor};
color: ${props => props.textColor};
`;
<DynamicDiv bgColor='papayawhip' textColor='palevioletred'>Dynamic Content</DynamicDiv>;
Server-Side Rendering
styled-components can be rendered on the server, allowing you to generate the required styles along with your HTML for faster initial load times. The example shows how to use ServerStyleSheet to collect styles during server-side rendering.
import { ServerStyleSheet, StyleSheetManager } from 'styled-components';
const sheet = new ServerStyleSheet();
<StyleSheetManager sheet={sheet.instance}>
<YourApp />
</StyleSheetManager>;
const styleTags = sheet.getStyleTags(); // gets all the tags from the sheet
Emotion is a performant and flexible CSS-in-JS library. It is similar to styled-components but offers a different API and additional features like composition patterns and the ability to work with plain objects instead of template literals.
JSS is an authoring tool for CSS which allows you to use JavaScript to describe styles in a declarative, conflict-free and reusable way. It differs from styled-components in its approach to styling, using JavaScript objects instead of tagged template literals.
Aphrodite is another CSS-in-JS library that allows you to write styles in JavaScript and attach them to your components. It focuses on performance by generating as little CSS as possible and supports server-side rendering, but it does not use tagged template literals.
Linaria is a zero-runtime CSS-in-JS library that extracts CSS to real CSS files during the build process. Unlike styled-components, which injects styles at runtime, Linaria aims to provide better performance by avoiding the runtime style injection.
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅
npm install --save styled-components
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!
styled-components
is compatible with both React (for web) and ReactNative – meaning it's the perfect choice even for truly universal apps! See the ReactNative section for more information
Note: If you're not using
npm
as your package manager, aren't using a module bundler or aren't sure about either of those jump to Alternative Installation Methods.
Made by Glen Maddern and Max Stoiber, supported by Front End Center and Thinkmill. Thank you for making this project possible!
This creates two react components, <Title>
and <Wrapper>
:
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;
`;
(The CSS rules are automatically vendor prefixed, so you don't have to think about it!)
You render them like so:
// Use them like any other React component – except they're styled!
<Wrapper>
<Title>Hello World, this is my first styled component!</Title>
</Wrapper>
Styled components pass on all their props. This is a styled <input>
:
import React from 'react';
import styled from 'styled-components';
// Create an <Input> component that'll render an <input> tag with some styles
const Input = styled.input`
font-size: 1.25em;
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
&:hover {
box-shadow: inset 1px 1px 2px rgba(0,0,0,0.1);
}
`;
You can just pass a placeholder
prop into the styled-component
. It will pass it on to the DOM node like any other react component:
// Render a styled input with a placeholder of "@mxstbr"
<Input placeholder="@mxstbr" type="text" />
Here is one input without any content showing the placeholder, and one with some content:
This is a button component that has a primary
state. By setting primary
to true
when rendering it we adjust the background and text color. (see tips and tricks for more examples of this pattern!)
import styled from 'styled-components';
const Button = styled.button`
/* Adapt the colors based on primary prop */
background: ${props => props.primary ? 'palevioletred' : 'white'};
color: ${props => props.primary ? 'white' : 'palevioletred'};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
export default Button;
<Button>Normal</Button>
<Button primary>Primary</Button>
Taking the Button
component from above and removing the primary rules, this is what we're left with – just a normal button:
import styled from 'styled-components';
const Button = styled.button`
background: white;
color: palevioletred;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
export default Button;
Let's say someplace else you want to use your button component, but just in this one case you want the color and border color to be tomato
instead of palevioletred
. Now you could pass in an interpolated function and change them based on some props, but that's quite a lot of effort for overriding the styles once.
To do this in an easier way you can call styled
as a function and pass in the previous component. You style that like any other styled-component. It overrides duplicate styles from the initial component and keeps the others around:
// Tomatobutton.js
import React from 'react';
import styled from 'styled-components';
import Button from './Button';
const TomatoButton = styled(Button)`
color: tomato;
border-color: tomato;
`;
export default TomatoButton;
This is what our TomatoButton
looks like, even though we have only specified the color
and the border-color
. Instead of copy and pasting or factoring out the styles into a separate function we've now reused them.
Note: You can also pass tag names into the
styled()
call, like so:styled('div')
. In fact, the styled.tagname helpers are just aliases ofstyled('tagname')
!
The above also works perfectly for styling third-party components, like a react-router
<Link />
!
import styled from 'styled-components';
import { Link } from 'react-router';
const StyledLink = styled(Link)`
color: palevioletred;
display: block;
margin: 0.5em 0;
font-family: Helvetica, Arial, sans-serif;
&:hover {
text-decoration: underline;
}
`;
<Link to="/">Standard, unstyled Link</Link>
<StyledLink to="/">This Link is styled!</StyledLink>
Note:
styled-components
generate a real stylesheet with classes. The class names are then passed to the react component (including third party components) via theclassName
prop. For the styles to be applied, third-party components must attach the passed-inclassName
prop to a DOM node. See Usingstyled-components
with existing CSS for more information!
CSS animations with @keyframes
aren't scoped to a single component but you still don't want them to be global. This is why we export a keyframes
helper which will generate a unique name for your keyframes. You can then use that unique name throughout your app.
This way, you get all the benefits of using JavaScript, are avoiding name clashes and get your keyframes like always:
import styled, { keyframes } from 'styled-components';
// keyframes returns a unique name based on a hash of the contents of the keyframes
const rotate360 = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;
// Here we create a component that will rotate everything we pass in over two seconds
const Rotate = styled.div`
display: inline-block;
animation: ${rotate360} 2s linear infinite;
`;
This will now rotate it's children over and over again, for example our logo:
<Rotate>< 💅 ></Rotate>
styled-components
has a ReactNative mode that works exactly the same, except you import the things from styled-components/native
:
import styled from 'styled-components/native';
const StyledView = styled.View`
background-color: papayawhip;
`;
const StyledText = styled.Text`
color: palevioletred;
`;
class MyReactNativeComponent extends React.Component {
render() {
<StyledView>
<StyledText>Hello World!</StyledText>
</StyledView>
}
}
We also support more complex styles (like transform
), which would normally be an array, and shorthands (e.g. for margin
) thanks to css-to-react-native
! Imagine how you'd write the property in ReactNative, guess how you'd transfer it to CSS and you're probably right:
const RotatedBox = styled.View`
transform: rotate(90deg);
text-shadow-offset: 10 5;
font-variant: small-caps;
margin: 5 7 2;
`
You cannot use the
keyframes
andinjectGlobal
helpers since ReactNative doesn't support keyframes or global styles. We will also log a warning if you use media queries or nesting in your CSS.
styled-components
has full theming support by exporting a wrapper <ThemeProvider>
component. This component provides a theme to all react components underneath itself in the render tree, even multiple levels deep.
To illustrate this, let's create a component that renders its children with a theme. We do so by wrapping all its children in a ThemeProvider
that has a theme
:
import { ThemeProvider } from 'styled-components';
const theme = {
main: 'mediumseagreen',
};
// Create a GreenSection component that renders its children wrapped in
// a ThemeProvider with a green theme
const GreenSection = (props) => {
return (
<ThemeProvider theme={theme}>
{props.children}
</ThemeProvider>
);
}
Second, let's create a styled component that adapts to the theme.
styled-components
injects the current theme via props.theme
into the components, which means you can adapt your component to the theme with interpolated functions.
We'll create a button
that adapts based on the main
property of the theme:
// Button.js
import styled from 'styled-components';
const Button = styled.button`
/* Color the background and border with theme.main */
background: ${props => props.theme.main};
border: 2px solid ${props => props.theme.main};
/* …more styles here… */
`;
Now, when we render the Button
inside a GreenSection
, it'll be green!
<GreenSection>
{/* Notice how there's no code changes for the button, it just
adapts to the theme passed from GreenSection! */}
<Button>Green Button!</Button>
<div>
<div>
<div>
{/* This works unlimited levels deep within the component
tree since we use React's context to pass the theme down. */}
<Button>Another green button!</Button>
</div>
</div>
</div>
</GreenSection>
See the theming doc for more detailed instructions.
The problem with the above code is that if the button is rendered outside a ThemeProvider
, it won't have any background or border!
There is an easy remedy though. Since Button
is just a react component we can assign defaultProps
, which will be used if no theme is provided:
// Button.js
import styled from 'styled-components';
const Button = styled.button`
/* Color the background and border with theme.main */
background: ${props => props.theme.main};
border: 2px solid ${props => props.theme.main};
/* …more styles here… */
`;
// Set the default theme, in our case main will be
// palevioletred if no other theme is specified
Button.defaultProps = {
theme: {
main: 'palevioletred',
},
};
See the documentation for more information about using styled-components
.
styled-components
with existing CSS: Some edge cases you should be aware of when using styled-components
with an existing CSS codebaseThere is (currently experimental) support for stylelint
– meaning you can take advantage of 150 rules to make sure your styled-components
CSS is solid!
See the stylelint-processor-styled-components
repository for installation instructions.
The one thing you lose when writing CSS in template literals is syntax highlighting. We're working hard on making proper syntax highlighting happening in all editors. We currently have support for Atom, Visual Studio Code, and soon Sublime Text.
This is what it looks like when properly highlighted:
@gandm, the creator of language-babel
, has added support for styled-components
in Atom!
To get proper syntax highlighting, all you have to do is install and use the language-babel
package for your JavaScript files!
There is an open PR by @garetmckinley to add support for styled-components
to babel-sublime
! (if you want the PR to land, feel free to 👍 the initial comment to let the maintainers know there's a need for this!)
As soon as that PR is merged and a new version released, all you'll have to do is install and use babel-sublime
to highlight your JavaScript files!
The vscode-styled-components extension provides syntax highlighting inside your Javascript files. You can install it as usual from the Marketplace.
We could use your help to get syntax highlighting support to other editors! If you want to start working on syntax highlighting for your editor, open an issue to let us know.
styled-components
grid-styled
: Responsive grid system (demo)react-aria-tooltip
: Simple & accessible ReactJS tooltip componentreact-boilerplate
: A highly scalable, offline-first foundation with the best developer experience and a focus on performance and best practicesBuilt something with styled-components
? Submit a PR and add it to this list!
These are some great articles and talks about related topics in case you're hungry for more:
If you're not using a module bundler or not using npm
as your package manager, we also have a global ("UMD") build!
You can use that via the unpkg
CDN to get styled-components
, the URL is https://unpkg.com/styled-components/dist/styled-components.min.js
.
To install styled-components
with bower you'd do:
bower install styled-components=https://unpkg.com/styled-components/dist/styled-components.min.js
To use it from your HTML, add this at the bottom of your index.html
, and you'll have access to the global window.styled
variable:
<script src="https://unpkg.com/styled-components/dist/styled-components.min.js" type="text/javascript"></script>
Licensed under the MIT License, Copyright © 2016 Glen Maddern and Maximilian Stoiber.
See LICENSE for more information.
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.
FAQs
CSS for the <Component> Age. Style components your way with speed, strong typing, and flexibility.
The npm package styled-components receives a total of 3,366,684 weekly downloads. As such, styled-components popularity was classified as popular.
We found that styled-components demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.