How to use styled components in ReactJS

Overview

In this shot, we will learn how to use the styled-components of the npm package in our ReactJS application. With styled-components, we can style our React application without worrying about duplicate class names and while maintaining our styles and so on.

Installation

We will run the following command in the terminal to install a React project:

npx create-react-app styledexample

To install the styled-components package inside our React project from the terminal, we will use the following command:

npm i styled-components

Example

Now, we’ll use the styled-components package to style a div, button, and an input field. We will then use backticks to style the HTML tags.

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);
Using styled-components in React

Explanation

Lines 5–7: We create a styled button called SubmitButton.

Lines 9–11: We create a styled input field called FormInput.

Lines 13–16: We create a styled div called Container.

Lines 20–23: We use these styled components as tags inside our application.

In the output, we can see how the styles are applied to their respective tags.

Free Resources