3 Ways to style in React

Recently, I have been creating a few clones using React and have encountered various ways to style in React. It was confusing to me as to why there was not a unique way to do so, but it gives more options to the developers and some methods would not be appropriate depending the situation.

In this article, I am going to explore the different methods of styling such as:

  • Inline Styling
  • styled-components
  • CSS Modules

Method #2: styled-components

With styled-components, we can write actual CSS in our JavaScript file. This means you can use all the features of CSS — like media queries, pseudo-selectors, nesting, etc. — in JavaScript.

First, we need to install it, so run the following in your React app’s directory:

npm install --save styled-components

In the following example on a Linkedin-clone project that I am working on, I used the styled component to style the ‘Join Now’ and ‘Sign In’ components.

I imported the styled-component package on top of my file, and wrote pure CSS in my Javascript file. This was new to me and I find it quite nice to use, as it is directly in our file so we can really see what we are styling. It could make files look really complicated if we get too much code and CSS to write to create a single component.

Method #3: CSS Modules

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default.

CSS class names and animation names are scoped globally by default. This can lead to conflict, especially in large stylesheets; one style can override another. This is the problem CSS Modules solves. CSS classes are only available within the component where they are used.

In this example, I’m going to style the Sign In button in my Linkedin-clone app using the CSS Modules. First, I am going to create a Login.module.css file in my components folder. Then I will import this file in my Login component, using styles as a name. Note that I could use any name but this the standard.

Finally, I will create a button tag and pass this style attribute to it, after adding some simple CSS to see the result.

References:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anil Kumar

Anil Kumar

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.