Styling your react app for beginners
Embracing component based styling
React encourages a method of styling focused on components instead of global styles found on static websites. Learning how to use this pattern effectively is crucial creating great web applications.
Basic component styling with CSS
Create-react-app comes bundled with webpack, a tool that bundles all your js and css into single files. If you use an import ./style.css
statement in a component.js
file it will automatically include that css in your final bundle.
All of your css is bundled into a single file so having unique class names for your components is very important.
The easiest naming convention to handle this is to use BEM. This means that you name your classes with Block(component)__element--modifier
.
For example a List component:
In that example I also split the component logic in the render function to make it easier to manage.
Your css will look something like this
You can remove the duplication on ListItem
if you use SASS with your react project (see create-react-app guide for info on how to add a css precompiler), so this becomes:
Controlling App layout
In react apps it is best to use the container/view + component (AKA smart + dumb component) pattern to define your views. So for example if you have a container containing a few components it will look like this:
It is considered bad practice to have styles in containers so creating layout components will decouple the styling and tidy up the markup, for example:
with styles:
However this is a bit too much boilerplate for simple layout components, so it is common to see them with inline styles. Here is the previous FlexCenter
component and a new one called FlexColAlignCenter
:
Then we can reuse them in our app wherever we want to control the layout of components, so the prior App
container becomes:
This is easier to read and maintain since the styles are separated completely from the container.
But what about global styles?
Global styles can be set in your index.css file that comes with create react app, for example fonts:
That’s all for this article!