I am currently available for freelance/contract work. Book a meeting so we can talk about your project.

Namespacing styled-components

Posted on

By keeping our styled-components in a separate file, we can import them under a namespace like “ui”. We can then tell by a component’s ui. prefix that it is one of our styled-components.

/* 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;
`
/* 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;
`
/* components/MyComponent/index.js */
import React from "react"
import SomeOtherComponent from "../SomeOtherComponent"
import * as ui from "./styles"
 
const MyComponent = ({ title, description }) => {
  return (
    <div>
      <ui.Title> <!-- must be a styled component -->
        {title}
      </ui.Title>
 
      <ui.Description> <!-- must be a styled component -->
        {description}
      </ui.Description>
 
      <SomeOtherComponent /> <!-- NOT a styled component -->
    </div>
  )
}
 
export default MyComponent
/* components/MyComponent/index.js */
import React from "react"
import SomeOtherComponent from "../SomeOtherComponent"
import * as ui from "./styles"
 
const MyComponent = ({ title, description }) => {
  return (
    <div>
      <ui.Title> <!-- must be a styled component -->
        {title}
      </ui.Title>
 
      <ui.Description> <!-- must be a styled component -->
        {description}
      </ui.Description>
 
      <SomeOtherComponent /> <!-- NOT a styled component -->
    </div>
  )
}
 
export default MyComponent
Debug
none
Grid overlay