Full CSS support for JSX without compromises
Full, scoped and component-friendly CSS support for JSX (rendered on the server or the client).
Code and docs are for v3 which we highly recommend you to try. Looking for styled-jsx v2? Switch to the v2 branch.
Firstly, install the package:
npm install --save styled-jsxNext, add styled-jsx/babel to plugins in your babel configuration:
{
"plugins": ["styled-jsx/babel"]
}Now add <style jsx> to your code and fill it with CSS:
export default () => (
)The following are optional settings for the babel plugin.
optimizeForSpeedBlazing fast and optimized CSS rules injection system based on the CSSOM APIs.
{
"plugins": [["styled-jsx/babel", { "optimizeForSpeed": true }]]
}When in production* this mode is automatically enabled.
Beware that when using this option source maps cannot be generated and styles cannot be edited via the devtools.
* process.env.NODE_ENV === 'production'
sourceMapsGenerates source maps (default: false)
styleModuleModule that the transpiled files should import (default: styled-jsx/style)
vendorPrefixesTurn on/off automatic vendor prefixing (default: true)
Next.js automatically configures styled-jsx with babel or swc, you don't have to configure it manually.
The example above transpiles to the following:
import _JSXStyle from 'styled-jsx/style'
export default () => (
)Unique classnames give us style encapsulation and _JSXStyle is heavily optimized for:
Notice that the outer `
)
### Global styles
To skip scoping entirely, you can make the global-ness of your styles
explicit by adding _global_.
```jsx
export default () => (
)
…
jsx
import Select from 'react-select'
export default () => (
)To make a component's visual representation customizable from the outside world there are three options.
Any value that comes from the component's render method scope is treated as dynamic. This makes it possible to use props and state for example.
const Button = props => (
<button>
{props.children}
<style jsx>{`
button {
padding: ${'large' in props ? '50' : '20'}px;
background: ${props.theme.background};
color: #999;
display: inline-block;
font-size: 1em;
}
`}</style>
</button>
)New styles' injection is optimized to perform well at runtime.
That said when your CSS is mostly static we recommend to split it up in static and dynamic styles and use two separate style tags so that, when changing, only the dynamic parts are recomputed/rendered.
const Button = props => (
<button>
{props.children}
<style jsx>{`
button {
color: #999;
display: inline-block;
font-size: 2em;
}
`}</style>
<style jsx>{`
button {
padding: ${'large' in props ? '50' : '20'}px;
background: ${props.theme.background};
}
`}</style>
</button>
)className togglingThe second option is to pass properties that toggle class names.
const Button = props => (
<button className={'large' in props && 'large'}>
{props.children}
<style jsx>{`
button {
padding: 20px;
background: #eee;
color: #999;
}
.large {
padding: 50px;
}
`}</style>
</button>
)Then you would use this component as either <Button>Hi</Button> or <Button large>Big</Button>.
style*best for animations
Imagine that you wanted to make the padding in the button above completely customizable. You can override the CSS you configure via inline-styles:
const Button = ({ padding, children }) => (
<button style={{ padding }}>
{children}
<style jsx>{`
button {
padding: 20px;
background: #eee;
color: #999;
}
`}</style>
</button>
)In this example, the padding defaults to the one set in <style> (20), but the user can pass a custom one via <Button padding={30}>.
It is possible to use constants like so:
import { colors, spacing } from '../theme'
import { invertColor } from '../theme/utils'
const Button = ({ children }) => (
<button>
{children}
<style jsx>{`
button {
padding: ${spacing.medium};
background: ${colors.primary};
color: ${invertColor(colors.primary)};
}
`}</style>
</button>
)
…
jsx
import React from 'react'
import ReactDOM from 'react-dom/server'
import { StyleRegistry, useStyleRegistry } from 'styled-jsx'
import App from './app'
function Styles() {
const registry = useStyleRegistry()
const styles = registry.styles()
return <>{styles}</>
}
export default (req, res) => {
const app = ReactDOM.renderToString(<App />)
const html = ReactDOM.renderToStaticMarkup(
<StyleRegistry>
<html>
<head>
<Styles />
</head>
<body>
)N.B. All the tags except for resolve don't support dynamic styles.
resolve and global can also be imported individually:
import { resolve } from 'styled-jsx/css'
import { global } from 'styled-jsx/css'If you use Prettier we recommend you to use the default css export syntax since the tool doesn't support named imports.
The css tag from styled-jsx/css can be also used to define styles in your components files but outside of the component itself. This might help with keeping render methods smaller.
import css from 'styled-jsx/css'
export default () => (
)
const button = css`
button {
color: hotpink;
}
`Like in externals styles css doesn't work with dynamic styles. If you have dynamic parts you might want to place them inline inside of your component using a regular <style jsx> element.
resolve tagThe resolve tag from styled-jsx/css can be used when you need to scope some CSS - for example, if you need to style nested components from the parent, such as the Link component in the example below.
It works by returning the generated scoped className and related styles.
import React from 'react'
import Link from 'some-library'
import css from 'styled-jsx/css'
const { className, styles } = css.resolve`
a { color: green }
`
export default () => (
)The resolve tag also supports dynamic styles, via template string interpolation:
import React from 'react'
import css from 'styled-jsx/css'
function getLinkStyles(color) {
return css.resolve`
a { color: ${color} }
`
}
export default props => {
const { className, styles } = getLinkStyles(props.theme.color)
return (
)
}resolve as a Babel macroIf you can't (or would rather not) make changes to your .babelrc, the resolve tag can be used as a Babel macro, thanks to the babel-plugin-macros system.
To set this up, first of all, install styled-jsx and babel-plugin-macros:
npm i --save styled-jsx
npm i --save-dev babel-plugin-macrosNext, add babel-plugin-macros to your Babel configuration:
{
"plugins": ["babel-plugin-macros"]
}You can then use resolve by importing it from styled-jsx/macro.
import css from 'styled-jsx/macro'
const { className, styles } = css.resolve`
a { color: green }
`
export default () => (
)create-react-appCreate React App comes with babel-plugin-macros already installed, so the only thing that needs to be done is to install styled-jsx:
npm i --save styled-jsxThen resolve can be imported from styled-jsx/macro and used the same way as in the example in the Using resolve as a Babel macro section above.
styled-jsx v3 comes with a webpack loader that lets you write styles in regular css files and consume them in React.
import styles from '../components/button/styles.css'
export default () => (
)To consume the styles in your component you can import them from your CSS file and render them using a <style jsx> tag. Remember to add the global prop if you want your styles to be global.
To use this feature you need to register the loader in your webpack config file, before babel-loader which will then transpile the styles via styled-jsx/babel
config: {
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: require('styled-jsx/webpack').loader,
options: {
type: 'scoped'
}
}
]
}
]
}
}The plugin accepts a type option to configure whether the styles should be scoped, global or resolve (see above). By default its values is set to scoped. `typ
Hydration errors when using React Compiler in Next.js
Adding Content Security Policy with Next.js + styled-jsx
Content Security Policy (CSP) should use the nonce attribute
Feature: Container-Queries support / Stylis update
Bug: cannot add 2 global styles together inside 1 component
Support Node.js ESM
Classname not compiled/passed-through for wrapper components
How to use styled-jsx with webpack and React only, without Babel and Next.js?
ReactDOMServer.renderToPipeableStream
if you are getting this error it means that your `css` tagged template literals were not transpiled.