My FeedDiscussionsHashnode Enterprise
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Different ways to style react component

Different ways to style react component

Ram's photo
Ram
·May 28, 2022·

2 min read

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.

index.html (2).png

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.

FT1-n0yVUAAcuRe.jpg

styled component

styled-component is a third party library allows to write css inside js.

carbon (36) (2).png

  • 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.

Longshore High School (4) (2).png

pre processors

pre processors allows us to use features which are not available in CSS.

Example:

  1. variables
  2. loops
  3. mixins
  4. 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

  1. Sass
  2. Less
  3. Stylus
  4. PostCSS

01 (2).png

That's it. we will see more about pre processors in upcoming posts.

Thanks !.