How to install and use styled components in react js?

Hi Friends 👋,

Welcome To aGuideHub!

To install and use styled components in React js, you have to use the npm or yarn package manager that is how you can install the styled components library into your project.

Today, I am going to show you, how to install and use styled components in react js.

install and use styled components

Install the following packages to use styled components in react js.

npm

npm install --save styled-components

yarn

yarn add styled-components

Table of contents

  • Set up the React project.
  • Import necessary components.
  • Use styled-components.

Step 1: Set up the React project.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import necessary components.

After installing styled-components, you have to import your React component. To do this, add the following line to the top of your Button.js file.

import styled from "styled-components";

Step 3: Use styled-components.

In this blog, see the short example to create a button and using styled.div element.

const Button = styled.div`
  width: 100px;
  cursor: pointer;
  text-decoration: none;
  color: white;
  background-color: purple;
  margin: 0 auto;
  font-size: 2rem;
`;

React styled-components example.

The code below is an example of this, In Button.js, to pass the value in background-color you have to take the help of a template string, in which using a ternary operator we can check the value of props.bg attribute, and set background-color accordingly You can set the value.

App.js

import Button from "./Button";

function App() {
  return (
    <div>
      <Button> Click </Button>
    </div>
  );
}

export default App;

Button.js

import styled from "styled-components";

const Button = styled.div`
  width: 100px;
  cursor: pointer;
  text-decoration: none;
  color: white;
  background-color: purple;
  margin: 0 auto;
  font-size: 2rem;
`;

export default Button;

Check the output of the above code example.

React, styles-component

Here, we are provided code sandbox links for the above program install and use styled components in React js. Then you can use whenever you went and do the changes as per your requirements.

Try it Yourself

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts