Skip to content

CSS in JS

ZΛNDΞR edited this page Dec 11, 2017 · 7 revisions

Stack

Emotion

Installation

yarn add emotion react-emotion

Emotion uses the Stylis, the CSS preprocessor internally. Stylis supports many Sass-like features as well as autoprefixing.

Emotion snippets

Emotion docs: https://github.com/emotion-js/emotion#documentation

Importing

import styled, {
  css,
  sheet,
  injectGlobal,
  keyframes,
  fontFace
} from 'react-emotion'

Basic example

import React from 'react'
import styled from 'react-emotion'
import { ds } from '../../theme'

const FooterEl = styled('footer')`
  text-align: center;
  margin-top: ${ds.spacing(3)};
`

const Footer = () => {
  return (
    <FooterEl>
      Made by <a href="https://zander.wtf">Zander</a>
    </FooterEl>
  )
}

export default Footer

Using props

const ButtonCSS = (props) => css`
  display: ${props.block ? 'block' : 'inline-block'};
  width: ${props.block ? '100%' : 'auto'};
export const FormGroup = styled('div')`
  margin-top: ${ds.spacing(2)};
  margin-bottom: ${ds.spacing(2)};
  display: ${props => props.horizontal ? `flex` : 'block'};
`

<FormGroup></FormGroup>

Codesandbox example

Extending styles

import styled, {
  css,
} from 'react-emotion'

const buttonCSS = css`
  cursor: pointer;
  border: none;
  margin: 0;
  border-radius: ${ds.get('borderRadius')};
  font-weight: ${ds.get('type.fontWeight.bold')};
`

export const Button = styled('button')`${buttonCSS};`

export const LinkButton = Button.withComponent('a')

<Button></Button>
<LinkButton></LinkButton>

See more of this example in this Codesandbox