Frontend Development 11 min read

How to Write CSS Elegantly in React

This article examines the problem of global CSS scope pollution in React components and presents three practical solutions—namespaces, CSS‑in‑JS, and CSS Modules—detailing their implementation, advantages, and trade‑offs, with code examples and guidance on when to use each approach.

政采云技术
政采云技术
政采云技术
How to Write CSS Elegantly in React

In modern single‑page applications built with React, separating CSS files does not guarantee isolation of styles, leading to unexpected visual side effects when multiple components import their own CSS files. The article first illustrates this issue with a typical project directory structure and conflicting .title selectors in comA.css and comB.css , which after bundling produce overlapping rules.

To address CSS scope pollution, three main strategies are discussed:

Solution 1: Namespaces

By prefixing class names with a component‑specific namespace (e.g., .comA .title and .comB .title ), styles are kept separate. The approach can be simplified with preprocessors like LESS or SASS, allowing nested rules such as:

.comA {
    .title { color: red; }
    /* other styles */
}
.comB {
    .title { font-size: 14px; }
    /* other styles */
}

When components are nested, additional BEM‑style naming (e.g., .comA__title ) ensures that parent styles do not leak into child components.

Solution 2: CSS‑in‑JS

CSS can be written directly in JavaScript, a method endorsed by the React team. Two popular libraries are highlighted:

reactCSS : defines style objects that can be conditionally merged. Example:

const styles = reactCSS({
  'default': { card: { background: '#fff', boxShadow: '0 2px 4px rgba(0,0,0,.15)' } },
  'zIndex-2': { card: { boxShadow: '0 4px 8px rgba(0,0,0,.15)' } }
}, { 'zIndex-2': props.zIndex === 2 });

class Component extends React.Component {
  render() {
    return (
      <div style={styles.card}>
        <div style={styles.title}>{this.props.title}</div>
        {this.props.children}
      </div>
    );
  }
}

styled‑components : uses tagged template literals to write CSS‑like strings that are attached to React components. Example:

const Button = styled.a`
  display: inline-block;
  border-radius: 3px;
  padding: 0.5rem 0;
  width: 11rem;
  background: transparent;
  color: white;
  border: 2px solid white;
  ${props => props.primary && css`
    background: white;
    color: palevioletred;
  `}
`;

render(
  <div>
    <Button href="https://github.com/styled-components/styled-components" target="_blank" rel="noopener" primary>GitHub</Button>
    <Button as={Link} href="/docs" prefetch>Documentation</Button>
  </div>
);

CSS‑in‑JS offers tight integration with component logic but introduces a learning curve.

Solution 3: CSS Modules

Webpack’s css-loader can be configured with modules: true to generate locally scoped class names. Example webpack configuration:

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        loader: 'css-loader',
        options: { modules: true }
      }
    ]
  }
};

In the component, styles are imported as an object and applied via className={styles.title} . After compilation, class names receive a hash suffix (e.g., .App__title--2qYnk ), guaranteeing uniqueness.

Summary and Recommendations

For UI component libraries with a stable maintainer team, the namespace approach is recommended because conventions are easier to enforce. In business codebases with many contributors, a combination of namespaces for outer containers and either CSS‑in‑JS or CSS Modules for inner styling provides the best balance between isolation and developer ergonomics.

When choosing between CSS‑in‑JS and CSS Modules, consider team familiarity: CSS Modules have lower intrusion, while CSS‑in‑JS enables sharing of JavaScript variables within styles. Consistency within a project is more important than the intrinsic superiority of one technique.

frontendreactCSS-in-JSWeb DevelopmentCSSCSS ModulesNamespaces
政采云技术
Written by

政采云技术

ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.