Notes

React Styled Components

Edit on GitHub

ReactJS
3 minutes
1#sudo npm i -g create-react-app
2yarn global add create-react-app
3
4create-react-app react-styled-components
5cd react-styled-components
6
7# npm i --save styled-components
8yarn add styled-components

Component Architecture

We usually have categories for the components..

src
├── components
│   ├── common
│   ├── containers
│   └── pages
├── index.css
├── logo.svg
└── index.js

Containers interact with data and have business logic, these generally won’t have any styles associated with them. They are responsible for interacting with data stores and passing it down to child components

Pages consist of top level pages, Home, Contact, Landing etc.

Common has things like buttons. These are a good starting point for styled components.

Traditional React Components

common
├── Button.css
└── Button.js
 1// Button.js
 2import React from 'react'
 3import './Button.css'
 4
 5const Button = ({ children }) => {
 6  return (
 7    <button className='btn'>
 8      { children }
 9    </button>
10  )
11}
12
13export default Button
1/*
2Button.css
3*/
4.btn {
5  background: plum;
6  border: none;
7  padding: 1em;
8}

React Styled Components

 1// Button.js
 2import React from 'react'
 3import styled from 'styled-components'
 4
 5const Button = styled.button`
 6  background: salmon;
 7  border: none;
 8  padding: 1em;
 9`
10
11export default Button
  • after styled. could be an valid HTML element: styled.button, styled.section, styled.h1 etc.

  • within the backticks you can add ANY valid CSS markup, e.g. media queries, nested CSS, pseudo-selectors etc.

  • the {children} are already taken care of

Conditional styles with props

1<Button danger>
2  Dragons!
3</Button>

Traditional way

 1// Button.js
 2
 3import React from 'react'
 4import './Button.css'
 5
 6// Conditional Styling based on props
 7const Button = ({ danger, children }) => {
 8  return (
 9    <button className={`btn ${danger ? ' btn-danger' : ''}`}>
10      { children }
11    </button>
12  )
13}
14
15export default Button
 1/*
 2Button.css
 3*/
 4
 5.btn {
 6  padding: 1em;
 7  border: none;
 8  font-weight: bold;
 9}
10
11.btn-danger {
12  background: #DC3545;
13  color: white;
14}

Styled components way

  • You have access to props from within the styled component
  • If danger has been passed as prop, render some more css
  • Look into tagged template literals for more on how this works
 1// Button.js
 2
 3import React from 'react'
 4import styled, { css } from 'styled-components'
 5
 6const Button = styled.button`
 7  padding: 1em;
 8  border: none;
 9  font-weight: bold;
10
11  /* If 'danger' has been passed as prop, render some more 'css' */
12  ${props => props.danger && css`
13    background: #DC3545;
14    color: white;
15  `}
16`
17
18export default Button