react-scoped-css
A build tool that scopes CSS to each React component. You keep plain className and plain CSS or SCSS. The build hashes class names per file, so styles never clash.
Plain CSS in React is global, so two components using the same class name can clash. CSS Modules and CSS-in-JS fix that, but only if you rewrite how every component is styled. I wanted scoping that leaves the code as it is.
What it does
Write CSS the way you already do
Plain className in JSX and plain selectors in CSS or SCSS. Your source files never change. Only the build output gets the hash.
<button className="btn">
Save
</button>
.btn { color: blue; }<button className="btn-a3f9b2c1">
Save
</button>
.btn-a3f9b2c1 { color: blue; }Same class names, no collisions
Two components can use the same class names and still look different. Here is how, one step at a time.
- 1
Two cards
TeamCardandTaskCardlook nothing alike. Both use the classes.cardand.title. - 2
TeamCard
Its own
.tsxand.scssfile, side by side.TeamCard.tsx<div className="card"> <p className="title">{name}</p> </div>TeamCard.scss.card { padding: 24px; background: #7c3aed; } .title { color: #fff; font-size: 20px; } - 3
TaskCard
The same class names, with different styles.
TaskCard.tsx<div className="card"> <p className="title">{title}</p> </div>TaskCard.scss.card { padding: 14px; border-left: 4px solid #2563eb; } .title { color: #0f172a; font-size: 15px; } - 4
The build
Each file gets its own hash. Your source still says
.card. The browser sees two different classes, so the styles never clash.
Leave globals alone
Class names that start with an excluded prefix stay exactly as written. Use it for shared styles and component libraries.
scopedCss({ exclude: ['global-', 'shared-'] })Get started
- 1
Install
Add the package to your project.
$npm install @dinesh-gamage/react-scoped-css - 2
Get the config
The
initcommand prints the snippet for your bundler.$npx @dinesh-gamage/react-scoped-css init - 3
Add it to your bundler
Vite, Next.js and webpack are supported.
// vite.config.ts import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { scopedCss } from '@dinesh-gamage/react-scoped-css/vite' export default defineConfig({ plugins: [react(), scopedCss({ exclude: ['global-'] })], }) - 4
Keep each stylesheet next to its component
Same name, same folder. That is how both files get the same hash.
src/components/Button/Button.tsxButton.scsssrc/components/Card/Card.tsxCard.scss