Codementor Events

HOW TO: Styled Components

Published Jul 04, 2018
HOW TO: Styled Components

Stress free CSS

Styled components is one of the must have libraries for every React project.
It makes the styling of components very simple and the effort to integrate it is minimal. Learn the basics here!

Concept

Styled-components will help you style your React components with declaring your components CSS as a React component.
The styling will be done in the same file as your component creation to keep things organized.

Create a red div from scratch

const RedDiv = styled.div`
  background: red;
`;

export default = () => (
  <RedDiv/>
);

The styled.* component creator works for pretty much every imaginable HTML element:

const styledImage = styled.img`
  ... styles
`;
const styledButton = styled.button`
  ...styles
`;

Extend an existing Component

Wrap a Styled-Component around it

import Heading from 'Heading';

const HeadingRed = styled(Heading)`
  color: Red;
`;
...

No CSS modules and class names anymore.

Dynamic Styling

Props on each styled component enable very easy dynamic styling.
Our Red div again:

const RedDiv = styled.div`
  background: red;
  border: ${(props) => props.showBorder ? '1px solid red' : 'none'};
`;

export default = ({ showBorder }) => (
  <RedDiv showBorder={showBorder} />
);

Notice how we return a different string for the border value based on the 'showBorder' Prop.
This makes your dynamic styling really easy!

Using Style Variables

Keep style values (colors, border width...) as JS variables in one file (styleVariables.js) and interpolate them with your Styled-Components where needed.
This will make it much easier for you to keep up style integrity and gives you one central place to controll them all at once.

Your styleVariables.js could look something like this:

export const $brandRed = '#ef093f';
export const $heavyFontWeight = 700;

Then import any of these to reuse the value:

import { $brandRed } from './styleVariables';
const RedDiv = styled.div`
  background: ${$brandRed};
`;

export default = () => (
  <RedDiv/>
);

Installation and more

Install:

yarn add styled-components

Import it where you need it with:

import styled from 'styled-components';

For more info, check out the great official docs:
https://www.styled-components.com/docs/basics#getting-started

Discover and read more posts from Lars Nolden
get started
post commentsBe the first to share your opinion
Show more replies