OneCompiler

How to use styled components in React

973


In this post let's see how to use styled-components in react

What are styled-components?

styled components are way to include css inside javascript files in react. They can be customized so much.

installation

Installing styled-components only takes a single command and you're ready to roll:

npm install --save styled-components

if you use yarn, add these in package.json field add

{
  "resolutions": {
    "styled-components": "^5"
  }
}

Getting Started

styled-components utilises tagged template literals to style your components.

It removes the mapping between components and styles. This means that when you're defining your styles, you're actually creating a normal React component, that has your styles attached to it.

This example creates two simple components, a wrapper and a title, with some styles attached to it:

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
`;

render(
    <Title>
      Hello World!
    </Title>
);

The output will be like

<img src="https://static.onecompiler.com/images/posts/3w3q6f2w2/sty.png" />