神刀安全网

Modular CSS with React

At Buffer , we love React and are incrementally moving a lot of our front-end codebase to it. With Flux on top of it, we just think it’s a very sane way to build a complex product made of smaller, modular apps. As such, we see each new small app and feature as a new React brick to add to that edifice.

I’ve been working on one of those new features lately, and have further fallen in love with how easy it is to build and reason about a React+Flux application. React makes it smooth to build the UI declaratively from meaningful components, and Flux brings a sensible data flow to the mix.

A lot of thought was given to the challenges that arise from building complex applications, and this stack solves a lot of them beautifully.

Yet, I still wasn’t sure how to make styling live up to React’s modularity and reusability.

Fortunately, there have been some very interesting developments in CSS-land recently, with a lot of patterns and tools emerging to make modular CSS a reality.

CSS-in-JS

Vjeux shared a lot of great ideas around leveraging JS to solve many challenges with CSS in React: CSS-in-JS . The rationale is that a lot of things that are naturally hard to achieve with CSS become significantly easier, just because they’re easier to achieve with JS.

The general idea is to write CSS in the form of JS object literals, which feel close enough to the natural syntax, and apply them to React components using the styles attribute. Styles can live in separate, modular files that get imported into JS modules using regular import statements.

CSS Modules

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default.

That’s the very simple premise of CSS Modules : each React component gets its own CSS file, which is scoped to that file and component. The magic happens at build time, when local class names – which can be super simple without risking collisions – are mapped to automatically-generated ones and exported as a JS object literal to use within React:

CSS Modules is deliberately very simple: it only adds a super small amount of new syntax to CSS to solve the CSS modularity challenge. Everything else remains the same.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Modular CSS with React

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮