At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

5 Best Way to Style React Components

  • By Saravana
  • June 13, 2019
  • 831 Views

In React, there are different approaches to style the Components. Each approach has some benefits and drawbacks. So choosing a single approach won’t serve the purpose. Use all of them wherever appropriate. Here we analyze the approaches one by one with the example.

1. Inline Styles

Inline style is the React’s inbuilt approach to style the component in which we can add the inline CSS with the style attribute. The style attribute will accept a JavaScript object with camelCase property as a key whose value is the style’s value.
https://github.com/agiratech-saran/react-component-styles/blob/master/inline-styles.txt

const headingStyles = {
color: '#fff',
backgroundColor: '#03a87c'
};
const heading = () => {
return <h1 style={headingStyles}>Hello World</h1>;
};

 
In the above example, we have created a variable headingStyles to store all the h1 element’s styles in camelCased JavaScript object. Later, that styles can be passed to the h1 element through the style attribute like,

style={headingStyles}
[/code]
And we can also directly pass the element like below,
https://github.com/agiratech-saran/react-component-styles/blob/master/direct-inline-styles.txt
[code]
const heading = () => {
return <h1 style={{color: '#fff', backgroundColor: '#03a87c'}} >Hello World</h1>;
}

 
Drawbacks of this approach are,

  • Unable to use the pseudo-classes(:hover, :active, :focus, ::before, ::after etc).
  • Can’t able to use media queries for Responsive components.
  • Can’t use vendor specific styles like -webkit-, -moz-, -ms- and -o-.
  • Duplication of code is possible.

 

2. CSS Stylesheet

Writing styles in an external CSS file and importing them in your components is another approach used in React, through which we can create a separate stylesheet for each component.
In JSX (roundedButton.jsx), className prob is used to add the class value to the element instead of the class attribute.
https://github.com/agiratech-saran/react-component-styles/blob/master/roundedButton.jsx

import React from "react";
import "./RoundedButton.css";
const RoundedButton = props => (
<button className="roundedButton">{props.children}</button>
);
export default RoundedButton;

 
Here the styles for the RoundedButton Component is imported from roundedButton.css.
https://github.com/agiratech-saran/react-component-styles/blob/master/roundedButton.css

.roundedButton {
color: #fff;
background-color: rgb(225, 0, 80);
border-radius: 10px;
padding: 10px 20px;
border: 0;
cursor: pointer;
}
.roundedButton:hover {
background-color: rgb(181, 2, 66);
}

 
To use this CSS stylesheet in react, webpack has to be configured with css-loader and style loader. Also, keep in mind that the projects which are created with create-react-app will have these loaders by default.
Advantages:

  • Style and content are separated.
  • Easy to maintain the modularity by creating a separate CSS file for each component and group the component and css in a single folder structure.

 

3. CSS Modules

According to the module definition here (https://github.com/css-modules/css-modules), A CSS Module is a CSS file in which all class names and animation names are scoped locally by default.
This is similar to writing styles in an external CSS file and importing them into the component. The only difference here is the styles are locally scoped to avoid the collisions of styles with other styles.
To brief it clearly, you can see the below examples to note how we have locally scoped the styles to avoid collisions,
Button.css
https://github.com/agiratech-saran/react-component-styles/blob/master/button.css

.error {
background-color: red;
}

 
another-stylesheet.css
https://github.com/agiratech-saran/react-component-styles/blob/master/another-stylesheet.css

.error {
color: red;
}

 
button.jsx
https://github.com/agiratech-saran/react-component-styles/blob/master/button.jsx

import React, { Component } from 'react';
import styles from './Button.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
render() {
// reference as a js object
return <button className={styles.error}>Error Button</button>;
}
}

 
Result
The rendered DOM has no clashes from other .error class names.
<!– This button has red background but not red text →

<button class="Button_error_ax7yz">Error Button</button>

 
The processed Button.css will be like,

.Button_error_ax7yz{
background-color: red;
}

 
During our build step, the compiler would search through that button.css file which we’ve imported, then looks through the JavaScript code we’ve written to make the .error class accessible via styles .error. Our build step would then process both these things into new, separate HTML and CSS files, with a new string of characters by replacing both the HTML class and the CSS selector class.
CSS Modules allows the scoping of CSS by automatically creating a unique class name of the format [filename]\_[classname]\_\_[hash].

4. Styled Components

Styled-components are created by defining the components with the help of ES6 template literal notation. CSS properties can be added in the component, just like how you do it using CSS. Therefore, all the styled-components will be generating the unique class names when the JS is parsed, and also it helps to inject the CSS into the DOM.
Installing Styled component module

npm install styled-components

Importing styled-components in React component

import styled from "styled-components"

https://github.com/agiratech-saran/react-component-styles/blob/master/styled-components.jsx

import React from "react";
import styled from "styled-components";
const RoundedButton = styled.button`
/* Adapt the colors based on primary prop */
background: ${props => props.primary ? "palevioletred" : "white"};
color: ${props => props.primary ? "white" : "palevioletred"};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
render(
<div>
<RoundedButton>Normal</RoundedButton>
<RoundedButton primary>Primary</RoundedButton>
</div>
);

 
In the above example, we have created a RoundedButton styled component. This component will create a button element with all the styles applied. Based on the primary prop, the background color and font color is changed.
The main advantage of this styling method can write pure CSS. JavaScript template literals that help us to use the full power of CSS to style components.
Go through the below link for more details,
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)

5. CSS Preprocessors

CSS Preprocessors are tools that converts non-CSS language into CSS, whereas most preprocessors using languages that are similar to CSS or an extension of it. Here the ultimate goal of a preprocessor is to provide a syntax that has more features, more readable or which requires less typing.
Flowing are few preprocessors available to style React components,

  • SASS/SCSS
  • LESS
  • Stylus

 

The End

Styling React components becomes a critical part of our development workflow. Choosing the best styling option has to be chosen based on the modularity and scalability. Instead of sticking to a single method of styling, try to use the combination of all these styling methods on your next projects.
[contact-form-7 404 "Not Found"]

Saravana

An enthusiastic Tech Lead with 7 plus years of experience in Web development arena. Owns legitimate experience in Ruby, Ruby On Rails, AngularJs, DevOps. Golang, Another add on, This young tech freak never miss a chance to get his hands on planting and Gardening even in his busy weekends.