bhylu.com

Advertisements

React CSS Modules

Use CSS Modules to avoid accidental name collisions while understanding their build-time scope.

How it works

A .module.css file exports a mapping from local names to generated class names. Vite transforms the import and includes the CSS in the build. The component refers to styles.card rather than hardcoding the generated output. This reduces accidental collisions between two features that both call a class card. It does not isolate inherited styles, reset browser defaults or create a security boundary.

Run the code

Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.

No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.

Example

src/main.jsx

import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';

import styles from './Item.module.css';
function App() {
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <article className={styles.card}>
        <h2>Market basket</h2>
        <p>Ready for a three-day loan.</p>
      </article>
    </main>
  );
}

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

Expected result

The item card receives the module’s blue border even though its final class name is generated.

Save the supporting module beside main.jsx. The default import is an object whose card property matches the authored class. Do not copy a hashed class name from browser inspection into JSX; it may change with the build. Shared design tokens can still use CSS custom properties. Scope solves a naming problem, while semantic structure and contrast remain the author’s responsibility.

Supporting files for this lab

src/Item.module.css

.card {
  border: 3px solid #034fa0;
  padding: 1rem;
}

For API contracts and version differences, use React’s official documentation.

Advertisements