Styled-components in React app

Having CSS in the components can be helpful. For more than a year, my favourite tool for managing CSS in React apps has been styled-components.

Getting started

To get started, download styled-component by running:

npm install --save styled-components

Now you are ready to use it in the app.

Styled-component usage

For example, let’s say you want to create a <H1 /> component that you will use in the app. First thing you need to do is import styled-components:

import styled from 'styled-components';

After that we can create our custom component, for example we want to make it font size 25px big, color white and letter spacing 1px:

const H1 = styled.h1`
font-size: 25px;
      color: white;
      letter-spacing: 1px;
`;

 As we’ve created our first custom H1, we can use it in render method:

render (
<H1>Our first custom H1</H1>
);

Advanced usage

If we want to send props to our custom component, we can do it easily! For example we want to change the color of the H1 text by sending prop in our component. We will do some small improvements to our custom component, in this case React with typescript:

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

interface Props {
      color?: string;
}
const H1 = styled.h1<Props>`
font-size: 25px;
      letter-spacing: 1px;
      ${props => props.color && `color: ${props.color};`}
`;

render (
<H1 color={'white'}>White H1</H1>
<H1 color={'blue'}>Blue H1</H1>
);

Now we will have displayed two H1 components, in the first text will be white color, and in the second will be blue.
Easy, right? Play around a bit and you will get the feel how easy it is to style your component. If you are interested in it, you can also go through the documentation and find out some more cool stuff.