React – Styling

Styling is a common requirement in web development. It does not matter whether plain HTML & CSS is used or advanced libraries like React, styling is essential to have good design layouts that will result in a great user experience.

Applying styles to a React application is not the same as adding a link tag to a CSS file in HTML. This is why beginners tend to get confused. We will take a look at all the different ways of styling in React.

Styling methods in React

In React, there are two different styling methods: Inline-CSS and External CSS Sheets.

Before you start, make sure that you have set up your react application using either:

  • create-react-app CLI (most recommended way)
  • or Webpack Bundler (not for beginners).

Inline CSS Styles in React

All React elements have a style attribute. Inline styles in React are applied using the style attribute of the React/JSX element. You need to pass an object as a value to this attribute.

The style object should contain the required CSS properties and values for styling.


The style object should follow these rules:

  • Property names with two or more words should use the camelCase naming syntax. Example: backgroundColor, marginLeft, borderTop etc.
  • The property values must be specified as a string unless it is a number value. Examples of property values: ‘10%’, ‘20px’, “1px solid” etc.
  • If any pixel value is required for properties like padding, margin, then we can simply use a number. React will automatically convert it to “px”.

Ways to Define the style object

You can define the style object in three different ways, whichever is suitable for you.

1. Defining inline

You can define the style object right inside the JSX expression of the style attribute.

<h2 style = {{ 
color: 'red', 
backgroundColor: 'orange', 
padding: 10, 
margin: 5 
}}> React Element </h2>

Don’t get confused by the double pair of braces {}. The outer braces are for the JSX expression. We are defining an object literal inside it.

2. Defining inside a variable

We can also store the style object inside a variable and use it in the style attribute.

const myStyle = { 
    color: 'red', 
    backgroundColor: 'orange', 
    padding: 10, 
    margin: 5 
}
<h2 style = {myStyle}> React Element </h2>

This is similar to the first method of defining the object inline but is more cleaner. You can define the style object inside or outside the class/functional component as you prefer.

3. Defining in some other file

If the style object is quite large with multiple properties, it is better to put it in an external file. The style object should be defined and exported from that file.

Benefits:

  • Keeps the React Components separate from style definitions. Hence, leaner files.
  • The style object can be imported and reused across different files.

This is how it is done:

/* Define the style in a separate file */
myStyle.js
    const myStyle = { 
color: 'red', 
backgroundColor: ‘orange’, 
padding: 10, 
margin: 5 
}
export default myStyle;

/* Now import and use wherever required */
MyComponent.jsx
    import myStyle from './myStyle.js';
const MyComponent = props => 
    <h2 style={ myStyle }>
        React Element
    </h2>
export default MyComponent;

External CSS Stylesheet with React

In the previous section, we were defining the style object in an external file. It was just an object defined in a separate JavaScript file. That is very different from using external CSS stylesheets.

Stylesheets are separate CSS files with a .css extension. Besides the benefit of sharing styles between different components, you can also write the usual CSS code here without any restriction.

/* write full-fleged CSS in an external stylesheet */
style.css
    .heading {
color: red;
background-color: orange;
padding: 10px;
}
button{
    padding: 5px;
}
/* 
Now simply import the CSS file into your component
and the styles will be applied automatically.
*/
MyComponent.js
    import './style.css';
const MyComponent = props => 
    <h2 class=”heading”>
        React Element
    </h2>
export default MyComponent;

Remember these two points:

  • The imported styles are applied globally, even on different components.
  • The CSS file should be imported without specifying the import name.
/* wrong way of importing CSS files */
import myStyle from './style.css';
/* correct way */
import './style.css';

CSS Modules

When you import a normal CSS file to a component, its styles are applied globally. It affects all the other components rendered by the application.

In CSS Modules, the styles are scoped locally. Using a CSS module, you can apply local styles to a component without polluting the global CSS namespace.

Creating a CSS Module in React

To create a CSS Module, name your CSS files in this structure:

[filename].module.css

The .module sub name is used to detect that you are using a CSS module. In the example below, we have defined a style for elements with the “highlight” class.

myStyle.module.css
    .highlight { 
        color: red;
        background-color: yellow;
}
.other {
margin: 10px;
}

Using a CSS Module

To use a CSS module in  React, you will have to import with a name. We can use that style and access the classes using the dot notation.

The code below imports the CSS module that was shown in the previous example.

MyComponent.js
    import myStyle from './myStyle.module.css';
const MyComponent = (props) => 
        <h2 class={myStyle.highlight}>
            Hello World
        </h2>
    export default MyComponent

Reason Why CSS Modules are locally scoped

A CSS module automatically converts its class names into unique identifiers which prevent the element from having two classes with the same name.

Check the screenshot below where the class name “highlight” in the code becomes a unique one: user_highlight_W2A2x. This is the benefit of using CSS modules. It creates the behavior of locally scoped styles in the imported file.

Using Sass with React

Sass is a CSS preprocessor library that scans files with extensions of .scss and compiles them into .css files. Using sass, we can add programming capabilities to our CSS files like variables, functions, loops, and conditional statements.

To use sass with React, we need to install a package called node-sass to our project using this command:

npm install node-sass

Once you install node-sass, you can simply start using files with .scss extension.

/* sass file using variables */
style.scss
    $my-color: red;
h1 {
        color: $my-color;
    }
Component.js
    import './style.scss';
    const MyComponent = props => 
        <div>
            <h1>Hello Sass</h1>
        </div>
    export default MyComponent;

Summary

You can define CSS styles inline or as an external stylesheet. If you want fine control over the CSS styles, it is helpful to use the CSS modules to create locally scoped styles.

If you want to go for libraries like Sass or Styled components, it’s up to you. They have their own set of advantages. Adding styles to a React application is easy if you understand the different possible ways.

 

Back to: React Tutorial > Learn React

Leave a Reply

Your email address will not be published. Required fields are marked *