There are multiple ways to style a react component. each way has their own pros and cons. we will discuss more on this.
inline style
One can easily inject styles to particular element using inline style method. in html you may seen like this.
pros
- Easily able to style particular HTML element directly.
cons
Can not able to use pseudo selectors/elements ex: ::hover, focus etc.
The more inline style used, the more the maintenance head ache is. because it increases number lines and introduces inconsistency with other styles sheets.
style sheets
Maintain style sheets separately and import globally (from app.js or index.js)
In react, in order to specify CSS class need to use className attribute. and you may wonder why JSX accepts className instead of class !!.
Since JSX is a extension of JavaScript and class is a reserved word in it, we need to use className instead of class.
pros
- Consistency with styles and maintenance is easy.
- We can use pseudo selectors and media queries.
cons
- we can’t able to maintain scope.
styled component
styled-component is a third party library allows to write css inside js.
under the hood it is a normal button only. so we can use it as HOC and add event listeners to it.
It injects all styles globally to the header and unique class names were generated. so it does not affect other element styles.
con
Since we writing CSS in js file itself, it makes maintenance hard when working with dedicated design team.
css modules
It is a feature comes in build with project created using create-react-app.
It exports styles as object. and we need use keys to assign respective class names.
Major advantage of using css modules is Scoping css to respective component in which it is imported.
Since it generates unique class names, there is no class name collisions.
pre processors
pre processors allows us to use features which are not available in CSS.
Example:
- variables
- loops
- mixins
- functions etc
It helps to automate the repetitive process (ex: using loops), thus reduces number of lines of code and increases maintainability.
They have their own special compiler which compiles and generates css file which we need to include in web page.
popularly used CSS preprocessors
- Sass
- Less
- Stylus
- PostCSS
That's it. we will see more about pre processors in upcoming posts.
Thanks !.