4. Four ways to style react components
This is the fourth part of my React tutorials. See the Intro to react.js here
There are four different options to style React components. All depend on your personal preferences and the specific complexity of your application.
If you want to add just a few style properties, then inline styling is the best option.
When you want to reuse your style properties in the same file then style-component are perfect.
When your application is more complex I recommend CSS Modules or regular CSS stylesheets.
1. CSS Stylesheet
- Simply import css file
import './DottedBox.css'so you can have a separate css file for each component.
2. Inline styling
In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style’s value, usually a string.
- We can create a variable that stores style properties and then pass it to the element like
- We can also pass the styling directly
3. CSS Modules
A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. Great article about css modules here.
- Similar to css we import css file
import styles './DashedBox.css'
- then we access to className as we access to object
:local(.className)-this when you use create-react-app because of webpack configurations
.className-this if you use your own react boilerplate.
To make CSS modules work with Webpack you only have to include the modules mentioned above and add the following loader to your
. . .
. . .
4. Styled-components 💅
- First we need to install
npm install styled-components --save
- Now we can create a variable by selecting a particular html element where we store our style keys
const Div = styled.htmlElemnet`color: pink`
- Then we use the name of our variable as a wrapper
<Div></Div>kind of react component:)
- Tips to use emoji icons key shortcut
All these ways of styling react components have props and coins.
It all boils down to both your own personal preferences and the specific complexity of your application.
I suggest you to make 4 projects, each using different way of style.
Next tutorial The Component Lifecycle