Thinking About CSS (with React)
CSS. You know it, you use it, you…might have a complicated relationship with it. When I first started making web apps, I looked at CSS as something of a necessary evil. I just wanted to do cool stuff with JavaScript, so I relied on frameworks — first Bootstrap, then Semantic UI — with a sprinkle of my own CSS to put things in their proper places. More recently, I’ve been building a few things aren’t well suited to to a framework, like my portfolio site, where I wanted to show off my design chops (such as they are) with something that looks a little less cookie cutter. In the process, I’ve actually come to (mostly) enjoy writing CSS, but I’m also beginning to find a need to change how I work with it.
To date, I’ve just been working with a single, monolithic .css file containing all of my selectors for a project…and that works. But my portfolio site is a responsive React single page application, with a little animation, and my App.css file is over 500 lines already — still manageable, but beginning to become unwieldy and hard to navigate. Time to find a new approach.
In this article, I’m going to briefly look at a few of the options available to write CSS, with an eye towards solutions that play well with React’s component based approach to building pages. I don’t expect to come to any conclusions about what’s best, I’d just like to be able to make a more informed decision quickly the next time I start a project.
CSS Modules
If you’re using a Webpack-based build process, like create-react-app provides, you can import stylesheets into your .js/.jsx file that, through the magic of Webpack, will be collected into a single .css file at build time. In terms of keeping your CSS organized, having a stylesheet dedicated to a single component is far neater, and more sensible, than searching through a wall of text for the selectors that apply to that component, but as the create-react-app docs note, this is a Webpack-specific syntax, and could be cause for concern if if you change your build process somewhere down the line.
styled-components
This is an interesting approach, if one that seems oriented more towards building a library of reusable components than the project-specific way of doing things that I’ve been using so far. With styled-components (install via NPM or your favorite package manager), you’re defining a component as a combination of an HTML element and the styles that apply to it, contained within a tagged template literal. Since this approach makes use of template literals, variables can be passed into the component, allowing styles to be defined via props. There’s a lot to like here, and while it’s not appropriate for every situation, I’m definitely considering using styled-components in the next big project that’s been bouncing around in my head recently.