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

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.