When it comes to styling our React application, there’s a list of options available for us to choose from. I’ve recently worked upon starting a fresh React project and since there are so many of these options, I wanted to take my time and explore them.
So, we could divide them into three major categories/ways of styling:
- CSS
- CSS-in-JS
- Component libraries
Each of these comes with their own perks and some pitfalls, you can decide which way to choose or you can use them in combination.
- CSS
Writing CSS in .css files is perhaps the simplest option to go for, where there’s not need to learn a single new thing. All we need is to setup the css-loader for Webpack (that too, is already set-up in create-react-app).
With this way, we’re not adding another layer in our application. Adding another layer such as a framework or library requires us to invest into that which is not a desired thing in longterm. It mean we’ll have to learn to write/use CSS in a different way and adds limitations as well.
The CSS written in .css files is independent of React or the application structure for the most part, thus it is easily reusable. By default, there’s not code-splitting here but there’s ways to work around that in case you have massive application.
Here’s a simple example:
- CSS-in-JS
This is a fairly new concept which came along and has been gaining popularity lately. The idea is to keep the styles attached to the components, mainly to achieve component-scoped styling and code-splitting. It might be a little tricky to get used to but libraries such as styled-components has now made it very easy to work with.
You could simply start from scratch or, there are component libraries built upon css-in-js as well.
Updating CSS dynamically without a refresh is pretty straight forward here, specifically for the purpose of theming.
Here’s an example with styled-components:
- Component Libraries
Just like how there have always been CSS frameworks, there are component libraries very similar to that. Component libraries such as Google Material or Ant-d comes with pre-built components to use. This sounds like it will be very quick for development, however, it takes a bit of learning and getting used to, to be working with any of these libraries. Here, the limitations might appear in our way of controlling customisability, component behaviour, updated features etc.
Components such as buttons are easier to use compared to using the more complicated, layout components. It not very convenient to work with and challenging to understand what's the behaviour on the rendered side of it.
I'd use CSS for a normal case and could go to css-in-js for more advanced requirements.
Let me know the ways that you prefer to use for your react applications!
Top comments (0)