Skip to content
This repository has been archived by the owner on Apr 22, 2024. It is now read-only.

Creating Styled Components

Andrew edited this page May 17, 2017 · 1 revision

Styled Components

Styled components exist to remove the mapping between styles and components. They allow a user to write actual CSS in JavaScript. This combination of styles and components greatly simplifies component styling.

Declaring a Component

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

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

The code above creates a react component called MyTitle. This component has all the CSS styles contained within the backticks. The color is orange, the font size is 1.5em and the text will be aligned in the center. MyTitle can now be used like a normal component:

<div>
  <MyTitle>Styled Components are Awesome!</MyTitle>
<div>

Dissecting The Code:

styled.h1` `; is simply a function call where the string contained in the backticks is a parameter. This function renders the <h1> component in the DOM. Once you add the CSS styles inside the backticks, a React component is made containing those styles for your use.

Styling all Components

Any existing can be made into a styled component (<img>, <p>, <div>, etc.). Even an already styled component can be styled. Just replace the styled.h1` `; function call with styled.div` `; or whichever component you wish to style.

Using Props

Styled components can adapt based on props passed into them. For example we can declare a button like this

const MyButton = styled.button`
  background: ${props => props.primary ? 'red' : 'white'};
  color: ${props => props.primary ? 'white' : 'red'};
  font-size: 1em;
  border-radius: 3px;
`;

Now we render MyButton:

<MyButton primary>Primary</MyButton>
<MyButton>Normal</MuButton>

The first MyButton has primary set to true so it will be white with a red background and the second has primary set to false so it will be red with a white background.

More Information

If you'd like to learn more, documentation for styled components can be found here