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
- CSS Modules
Method #1: Inline styling of React components
If you are familiar with basic HTML, you will know that it is possible to add your CSS inline. This is similar in React.
We can add inline styles to any React component we want to render. These styles are written as attributes and are passed to the element.
Here in my facebook clone, I used some inline styles to add a fontSize equal to large to the 5 Icons that will be display at the top of the page. Without this inline CSS, the icon would look smaller which is not what I was looking for.
I am also adding for the purpose of this article an inline CSS to create a new text, showing how to write multiple items to the object that we want to add
Now, in the code above, I just added a few properties to the elements I styled. However, imagine I had to add more and more styles to the element. This is where the inline method breaks down because it will not look clean.
A way to correct that is to create a style object variable. This object is then passed to the element as an attribute.
Here I added a CSSDiv variable and a CSSH2 variable and passed them as argument to the element. This gives the same end result but allows to write CSS more easily if we need to give it more options.
Method #2: styled-components
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.
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.
I worked on creating a few clones lately, and my preferred method was using the BEM convention. I found it really easy to use and organize my files by creating a related css file to each component.