Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

styled-jsx

> 前端框架
Open source

Full CSS support for JSX without compromises

7.8K stars0 likes0 views
WebsiteGitHub

About

Full CSS support for JSX without compromises

styled-jsx

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.

  • Getting started
  • Configuration options
    • optimizeForSpeed
    • sourceMaps
    • styleModule
    • vendorPrefixes
  • Features
  • How It Works
    • Why It Works Like This
  • Targeting The Root
  • Global styles
    • One-off global selectors
  • Dynamic styles
    • Via interpolated dynamic props
    • Via className toggling
    • Via inline style
  • Constants
  • Server-Side Rendering
  • External CSS and styles outside of the component
    • External styles
    • Styles outside of components
    • The resolve tag
    • Styles in regular CSS files
  • CSS Preprocessing via Plugins
    • Plugin options
    • Example plugins
  • Rendering in tests
  • FAQ
    • Warning: unknown jsx prop on <style> tag
    • Can I return an array of components when using React 16?
    • Styling third parties / child components from the parent
    • Some styles are missing in production
    • Build a component library with styled-jsx
  • Syntax Highlighting
  • ESLint
  • TypeScript
  • Credits

Getting started

Firstly, install the package:

bash
npm install --save styled-jsx

Next, add styled-jsx/babel to plugins in your babel configuration:

json
{
  "plugins": ["styled-jsx/babel"]
}

Now add <style jsx> to your code and fill it with CSS:

javascript
export default () => (
  

)

Configuration options

The following are optional settings for the babel plugin.

optimizeForSpeed

Blazing fast and optimized CSS rules injection system based on the CSSOM APIs.

json
{
  "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'

sourceMaps

Generates source maps (default: false)

styleModule

Module that the transpiled files should import (default: styled-jsx/style)

vendorPrefixes

Turn on/off automatic vendor prefixing (default: true)

Features

  • Full CSS support, no tradeoffs in power
  • Runtime size of just 3kb (gzipped, from 12kb)
  • Complete isolation: Selectors, animations, keyframes
  • Built-in CSS vendor prefixing
  • Very fast, minimal and efficient transpilation (see below)
  • High-performance runtime-CSS-injection when not server-rendering
  • Future-proof: Equivalent to server-renderable "Shadow CSS"
  • Source maps support
  • Dynamic styles and themes support
  • CSS Preprocessing via Plugins

Using in Next.js

Next.js automatically configures styled-jsx with babel or swc, you don't have to configure it manually.

How It Works

The example above transpiles to the following:

javascript
import _JSXStyle from 'styled-jsx/style'

export default () => (
  

)

Why It Works Like This

Unique classnames give us style encapsulation and _JSXStyle is heavily optimized for:

  • Injecting styles upon render
  • Only injecting a certain component's style once (even if the component is included multiple times)
  • Removing unused styles
  • Keeping track of styles for server-side rendering

Targeting The Root

Notice that the outer `

)

bash

### Global styles

To skip scoping entirely, you can make the global-ness of your styles
explicit by adding _global_.

```jsx
export default () => (
  

)

…

bash
jsx
import Select from 'react-select'
export default () => (
  

)

Dynamic styles

To make a component's visual representation customizable from the outside world there are three options.

Via interpolated dynamic props

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.

javascript
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.

javascript
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>
)

Via className toggling

The second option is to pass properties that toggle class names.

javascript
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>.

Via inline 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:

javascript
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}>.

Constants

It is possible to use constants like so:

javascript
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>
)

…

bash
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:

javascript
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.

Styles outside of components

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.

javascript
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.

The resolve tag

The 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.

javascript
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:

javascript
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 (
    

  )
}

Using resolve as a Babel macro

If 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:

bash
npm i --save styled-jsx
npm i --save-dev babel-plugin-macros

Next, add babel-plugin-macros to your Babel configuration:

json
{
  "plugins": ["babel-plugin-macros"]
}

You can then use resolve by importing it from styled-jsx/macro.

javascript
import css from 'styled-jsx/macro'

const { className, styles } = css.resolve`
  a { color: green }
`

export default () => (
  

)
Usage with create-react-app

Create React App comes with babel-plugin-macros already installed, so the only thing that needs to be done is to install styled-jsx:

bash
npm i --save styled-jsx

Then 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.

Styles in regular CSS files

styled-jsx v3 comes with a webpack loader that lets you write styles in regular css files and consume them in React.

javascript
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

javascript
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

Issues· 83 open

View all issuesOpen on GitHub
  • #859

    Hydration errors when using React Compiler in Next.js

    Updated Nov 24, 2025
  • #657

    Adding Content Security Policy with Next.js + styled-jsx

    Updated Feb 18, 2025
  • #854

    Content Security Policy (CSP) should use the nonce attribute

    Updated Dec 9, 2024
  • #853

    Feature: Container-Queries support / Stylis update

    Updated Dec 4, 2024
  • #852

    Bug: cannot add 2 global styles together inside 1 component

    Updated Nov 28, 2024
  • #640

    Support Node.js ESM

    Updated Nov 8, 2024
  • #713

    Classname not compiled/passed-through for wrapper components

    Updated Aug 18, 2024
  • #837

    How to use styled-jsx with webpack and React only, without Babel and Next.js?

    Updated May 11, 2024
  • #840

    ReactDOMServer.renderToPipeableStream

    Updated Oct 19, 2023
  • #685

    if you are getting this error it means that your `css` tagged template literals were not transpiled.

    Updated Oct 9, 2023

> Tags

JavaScriptcsscss-in-jsdynamic-stylesjsx

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架