From styled-components
Adopt Vitus Labs in a styled-components app. Keep styled-components through its connector, or switch to @vitus-labs/styler.
You can bring Vitus Labs into a styled-components codebase in two ways:
| Option A: keep styled-components | Option B: switch to styler | |
|---|---|---|
| Your existing components | Unchanged | Imports change, plus a short list of API differences |
| Vitus components (elements, rocketstyle, coolgrid, …) | Render through styled-components | Render through @vitus-labs/styler |
| SSR setup | Unchanged (ServerStyleSheet / registry stays) | Removed: React 19 <style precedence> handles it |
| CSS engine in the bundle | styled-components (17.89 KB min+gz) | styler (6.98 KB min+gz) |
Sizes are minified + gzipped with React external (from the styler bundle-size table).
A common path is to do A first (ship Vitus components without touching anything else), then move to B once your own components are converted.
Option A: keep styled-components
All Vitus packages go through @vitus-labs/core's engine interface, not a specific CSS-in-JS library. @vitus-labs/connector-styled-components plugs styled-components into that interface.
1. Check versions
The connector's peer dependencies are styled-components >= 6, @vitus-labs/core and react >= 19. If you are on styled-components v5, upgrade to v6 first.
2. Install
npm install @vitus-labs/core @vitus-labs/connector-styled-componentsThen add the Vitus packages you want, for example @vitus-labs/elements @vitus-labs/unistyle @vitus-labs/rocketstyle. @vitus-labs/styler is not needed: the Vitus packages only list it as a dev dependency.
3. Call init() before anything renders
import { init } from '@vitus-labs/core'
import * as connector from '@vitus-labs/connector-styled-components'
init({
...connector,
component: 'div',
textComponent: 'span',
})The connector exports css, styled, keyframes, createGlobalStyle, useTheme and provider (styled-components' ThemeProvider) as named exports. There is no default export, so use a namespace import. Every export is a straight re-export of styled-components.
Import this file once at the top of your entry point (main.tsx, layout.tsx, …).
4. Provide the theme through a Vitus Provider
The Vitus Provider (from @vitus-labs/core, @vitus-labs/unistyle or @vitus-labs/rocketstyle) fills the internal Vitus context and renders the engine's ThemeProvider with the same theme. Swap your styled-components ThemeProvider for it and pass one theme with both your keys and the Vitus keys:
import { Provider } from '@vitus-labs/rocketstyle'
const theme = {
rootSize: 16,
breakpoints: { xs: 0, sm: 576, md: 768, lg: 992, xl: 1200 },
// your existing styled-components theme keys
colors: { primary: '#0d6efd', text: '#212529' },
}
export const App = () => (
<Provider theme={theme} mode="light">
{/* existing styled-components see props.theme / useTheme() as before */}
<Routes />
</Provider>
)The Provider renders only its children when theme is empty.
5. Keep your SSR setup
Vitus components now produce styled-components, so your existing SSR setup (the ServerStyleSheet registry in Next.js App Router, or _document collection in the Pages Router) collects their CSS too. Nothing to change.
Caveats
- No
useCSS. The styled-components connector does not exportuseCSS: styled-components v6 has no public API that turns acssresult into a class name without a styled component. No Vitus package needs it. - Types: the connector augments core's
CSSEngineResultwith the return type of styled-components'css, socssfrom@vitus-labs/coreis typed as a styled-componentsRuleSet.
See Connectors for the full interface and how init() works.
Option B: switch to styler
@vitus-labs/styler has a styled-components-style API: tagged templates, styled.tag, as, $ transient props, refs, theming, keyframes, createGlobalStyle, component selectors and styled(StyledComponent) extension. Most files only need their import changed, but a few APIs are missing or work differently. Go through the table below before you start.
API mapping
| styled-components | @vitus-labs/styler | Notes |
|---|---|---|
import styled from 'styled-components' | import { styled } from '@vitus-labs/styler' | Named export only, no default export |
styled.div`…`, styled(Comp)`…` | Same | A wrapped component receives className |
css`…` | Same | Returns a lazy CSSResult; nesting, arrays and conditional (false / null) interpolations work |
keyframes`…` | Same | Tagged template only, no dynamic interpolations. Coerces to its name, so animation: ${fade} 1s works in plain strings too |
createGlobalStyle | Same | Returns a component. Mount-scoped and ref-counted (see below) |
ThemeProvider | Same | Object themes replace the outer theme (styled-components merges them); use a function theme to extend |
useTheme() | Same | Returns {} outside a provider |
withTheme(Comp) | Not provided | Call useTheme() inside the component |
ThemeContext / ThemeConsumer | Not exported | Call useTheme() |
as prop | Same | Never forwarded to the element. forwardedAs is not supported |
$transient props | Same | Never forwarded, not even to wrapped components |
.withConfig({ shouldForwardProp }) | styled(tag, { shouldForwardProp }) | Filter signature is (prop) => boolean, with no default validator argument. On a DOM tag a custom filter replaces the built-in HTML filter |
.attrs(…) | Not on styled | Use @vitus-labs/attrs or a wrapper component (see below) |
${Button} component selector | Same, for static components only | Interpolating a dynamic styled component throws [styler] … cannot be a selector (needs a static template) |
styled(StyledComp) | Same | Folded into one component; the extension wins |
css prop (Babel plugin) | Not supported | Use styled or useCSS() + className |
ServerStyleSheet, StyleSheetManager | Not needed / not provided | SSR is automatic with React 19 <style precedence> |
styled.div<Props> generics | Not supported | styled is not generic; drop the type argument (interpolation props are typed loosely) |
declare module 'styled-components' { interface DefaultTheme } | declare module '@vitus-labs/styler' { interface DefaultTheme } | Same augmentation pattern |
Two additions with no styled-components equivalent: useCSS(template, props?) returns a class name without a wrapper component, and the boost: true option doubles the selector for (0,2,0) specificity. See Styler.
Step-by-step
1. Install and re-point Vitus packages
npm install @vitus-labs/styler @vitus-labs/core @vitus-labs/connector-styler import { init } from '@vitus-labs/core'
- import * as connector from '@vitus-labs/connector-styled-components'
+ import * as connector from '@vitus-labs/connector-styler'
init({ ...connector, component: 'div', textComponent: 'span' })@vitus-labs/styler peer-depends on @vitus-labs/core and react >= 19. Your own components (@vitus-labs/styler) and the Vitus components (through connector-styler) now share one engine and one stylesheet.
2. Replace imports
- import styled, { css, keyframes, createGlobalStyle, ThemeProvider, useTheme } from 'styled-components'
+ import { styled, css, keyframes, createGlobalStyle, ThemeProvider, useTheme } from '@vitus-labs/styler'The default import becomes a named import. A find-and-replace on from 'styled-components' plus fixing the default import covers most files.
3. Remove the SSR plumbing
Styled components render a <style href precedence="medium"> next to their output on the server, and React 19 hoists, dedupes and orders those tags (global styles use precedence="low"). Delete:
- the Next.js App Router registry (
ServerStyleSheet+StyleSheetManager+useServerInsertedHTML) and its wrapper inlayout.tsx ServerStyleSheetcollection in a Pages Router_document(getInitialProps,sheet.collectStyles,sheet.getStyleElement()). Check that the server HTML contains the<style data-precedence>tags. If your renderer doesn't emit them, use manual mode (below)compiler: { styledComponents: true }innext.configorbabel-plugin-styled-components(unless you still have other styled-components code)
You do not need a per-request createSheet() on the default path. createSheet() is for the manual SSR mode, meant for runtimes that don't process <style precedence>. On hydration styler reads the SSR tags, so rules aren't injected twice.
4. Fix theme usage
-
Nested providers: styled-components merges a nested object theme into the outer one; styler replaces it. Turn partial nested themes into functions:
const withAccent = (outer) => ({ ...outer, colors: { ...outer.colors, primary: '#d63384' } }) <ThemeProvider theme={withAccent}>…</ThemeProvider>Define the function outside render so the memoized value stays stable.
-
withTheme/ThemeConsumer/useContext(ThemeContext)→useTheme(). -
Components wrapped with
styled(MyComponent)that readprops.theme→useTheme(). Styler resolves interpolations with the context theme but doesn't pass it on to a wrapped component (an explicitthemeprop is still forwarded):function MyCard({ className, children }) { const theme = useTheme() // not props.theme return <div className={className} data-mode={theme.mode}>{children}</div> } const Card = styled(MyCard)` padding: ${(p) => p.theme.spacing.md}px; ` -
Type augmentation: move
interface DefaultThemetodeclare module '@vitus-labs/styler'. -
If you use Vitus components, keep using the Vitus
Providerfrom Option A, step 4. Throughconnector-stylerit renders styler'sThemeProvider.
5. Replace .attrs()
Styler's styled has no .attrs(). You have two options.
A wrapper component:
const BaseInput = styled.input`
border: 1px solid ${(p) => p.theme.colors.border};
`
const TextInput = (props) => <BaseInput type="text" {...props} />Or the chainable @vitus-labs/attrs factory. Explicit props win over attrs, like styled-components:
import attrs from '@vitus-labs/attrs'
const TextInput = attrs({ name: 'TextInput', component: BaseInput })
.attrs({ type: 'text' })
.attrs<{ small?: boolean }>(({ small }) => ({ $size: small ? 'sm' : 'md' }))An attrs (or rocketstyle) component hoists the wrapped component's statics, so styled(TextInput) creates a wrapper instead of folding into BaseInput.
6. Fix .withConfig and generics
- const Input = styled.input.withConfig({
- shouldForwardProp: (prop, defaultValidator) => prop !== 'hasError' && defaultValidator(prop),
- })<{ hasError?: boolean }>`
+ const Input = styled('input', {
+ shouldForwardProp: (prop) => prop !== 'hasError',
+ })`
border-color: ${(p) => (p.hasError ? 'red' : 'gray')};
`On a DOM tag a custom shouldForwardProp decides alone, and the built-in HTML/SVG allowlist no longer applies. Reject any other non-DOM props yourself, or use $ props, which never need a filter.
7. Check component selectors
${Icon} works when Icon has no function interpolations. If it is dynamic, styler throws at creation time. Either make the target static (move the dynamic part to a $ prop on a child, or into a separate component), or target it with a class or data-* attribute.
8. Review styled(StyledComponent) overrides
Extending a styled component folds base and extension into one component and one rule, with the base first and the extension after. The extension's declarations always win, $ props reach the base's interpolations, and ${Base} selectors still match the extension. This is the styled-components v6 behaviour, so most code is unaffected.
9. Global styles and keyframes
createGlobalStylerules are inserted when the first instance mounts and removed when the last one unmounts. A dynamic global whose value changes (e.g. a light/dark toggle) replaces its previous rules. Keep the global mounted for as long as you need it.keyframesis injected immediately. On the server, any@keyframesa component or global style references are shipped inside its<style precedence>tag, so animations work in SSR HTML.
10. Nesting and leftovers
- Nesting is passed to the browser as native CSS nesting (no preprocessor).
&:hover,& h2,&.activework. Sass-style suffix concatenation (&-icon) does not. Styler adds no vendor prefixes.@media/@supports/@containerinside a rule are split into top-level rules for you. - Snapshot serializers such as
jest-styled-componentshave no styler counterpart. Class names arevl-<hash>. - Remove
styled-componentsand@vitus-labs/connector-styled-componentsfrompackage.jsononce nothing imports them.
Find what needs attention
grep -rnE "from 'styled-components'|\.attrs\(|\.withConfig\(|withTheme|ThemeConsumer|ThemeContext|ServerStyleSheet|StyleSheetManager|forwardedAs|styled\.[a-z]+<|styled\([A-Za-z]+\)<" srcAlso search for the css= prop if you used the Babel plugin.
Related
- Styler: engine reference and 2.9 notes
- Styler › Theming:
ThemeProvider, function themes,useTheme - Styler › API:
createSheet, SSR and manual mode - Connectors: the engine interface and
init() - From Emotion
Last updated on