Fire tips tagged “styled-components

Namespacing styled-components

If you keep your styled-components in a separate file, you can import them under a namespace like “ui”. If a component’s name then begins with ui., you can then tell it is one of your styled-components.

/* ./MyComponent/styles.js */
import styled from 'styled-components'

export const Title = styled.h1`
  font-size: 2rem;
  line-height: 1.35;
`

export const Description = styled.p`
  font-size: 1.6rem;
  line-height: 1.5;
`
/* ./MyComponent/index.js */
import React from 'react'
import SomeOtherComponent from '../SomeOtherComponent'
import * as ui from './styles'

const MyComponent = ({ title, description }) => {
  return (
    <div>
      <ui.Title>
        {title}
      </ui.Title>

      <ui.Description>
        {description}
      </ui.Description>

      <SomeOtherComponent />
    </div>
  )
}

export default MyComponent

Combining arrow functions in styled-components

Instead of using many arrow functions to extract the theme in your styled-components, you can group them and do them all in one block.

const Button = styled.button`
  box-shadow: ${({ theme }) => theme.boxShadows.medium};
  color: ${({ theme }) => theme.colors.white};
  font-weight: ${({ theme }) => theme.fontWeights.semibold};
  margin: 0;
`;

const Button = styled.button`
  ${({ theme }) => `
    box-shadow: ${theme.boxShadows.medium};
    color: ${theme.colors.white};
    font-weight: ${theme.fontWeights.semibold};
  `}
  margin: 0;
`;

Destructuring props in styled-components

Find yourself writing props. over and over in your styled-components? Destructure them to reduce the noise.

const Post = styled.article`
  background: ${props =>
    props.isFeatured ? props.theme.yellow : props.theme.white
  };
`;

const Post = styled.article`
  background: ${({ isFeatured, theme }) =>
    isFeatured ? theme.yellow : theme.white
  };
`;