styled-components in create-react-app

2023-03-18 hit count image

Let's see how to apply and use styled-components to the React project created by create-react-app.

create-react-app series

This blog post is a series. You can see other blog posts of the series on the list.

Outline

In this blog post, I’ll show how to apply styled-components to the React project.

This blog post will use the React project with TypeScript, and you can see the source code on the link below.

Create project

Execute the command below to create a React project.

npx create-react-app my-app --template=typescript

And then, execute the command below to start the React project.

# cd my-app
npm start

If you don’t have any problem, you can see the screen below on the browser.

create-react-app with styled-components

Install styled-components

We need to install the styled-components library to apply it to the React project created by create-react-app. Execute the command below to install the styled-components library.

npm install --save styled-components

And then, we use TypeScript on the React project, so execute the command below to install styled-components types and test library.

npm install --save-dev @types/styled-components jest-styled-components

How to use

Let’s make a simple component with styled-components. Open ./src/App.tsx file and modify it like below.

import React from 'react';
import Styled from 'styled-components';

const Container = Styled.div`
  background: red;
  width: 100%;
`;
const Label = Styled.div`
  color: white;
  padding: 20px;
`;

const App = () => {
  return (
    <Container>
      <Label>Hello World</Label>
    </Container>
  );
}

export default App;

We can write the style in JSX with styled-components like above.

And then, delete the unused files below.

  • App.css
  • logo.svg

You can see more usages on the official homepage.

Completed

We’ve seen how to apply styled-components to the React project created by create-react-app in this blog post. And the, we’ve seen simple usage of styled-components.

From now on, let’s make styles in JSX file with styled-components.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts