• Basics
  • Coming from Styled Components

Coming from Styled Components

How do Styled Components for CSS Modules work within a component?

If you're familiar with Styled Components, you'll be used to doing something like this:

import React, { useState } from 'react'
import styled from 'styled-components'
 
const StyledCounter = styled.div`
  /* ... */
`
const Paragraph = styled.p`
  /* ... */
`
const Button = styled.button`
  /* ... */
`
 
const Counter = () => {
  const [count, setCounter] = useState<number>(0);
 
  const increment = () => setCounter((count) => count + 1)
  const decrement = () => setCounter((count) => count - 1)
 
  render() {
    return (
      <StyledCounter>
        <Paragraph>{count}</Paragraph>
        <Button onClick={increment}>+</Button>
        <Button onClick={decrement}>-</Button>
      </StyledCounter>
    )
  }
}

Because a Styled Components for CSS Modules is just a component generator that receives classes from CSS Modules imports, we'd write Counter like this:

import React, { useState } from 'react'
import styled from '@helloinnovation/styled'
import styles from './styles.module.css'
 
const StyledCounter = styled.div(styles.wrapper)
const Paragraph = styled.p(styles.content)
const Button = styled.button(styles.button)
 
const Counter = () => {
  const [count, setCounter] = useState<number>(0);
 
  const increment = () => setCounter((count) => count + 1)
  const decrement = () => setCounter((count) => count - 1)
 
  render() {
    return (
      <StyledCounter>
        <Paragraph>{count}</Paragraph>
        <Button onClick={increment}>+</Button>
        <Button onClick={decrement}>-</Button>
      </StyledCounter>
    )
  }
}

Define Styled Components outside of the render method

It is important to define your styled components outside of the render method, otherwise it will be recreated on every single render pass. Defining a styled component within the render method will thwart caching and drastically slow down rendering speed, and should be avoided.

Write your styled components the recommended way:

const StyledWrapper = styled.div(/* */)
 
const Wrapper = ({ message }) => {
  return <StyledWrapper>{message}</StyledWrapper>
}

Instead of:

const Wrapper = ({ message }) => {
  // WARNING: THIS IS VERY VERY BAD AND SLOW, DO NOT DO THIS!!!
  const StyledWrapper = styled.div(/* */)
 
  return <StyledWrapper>{message}</StyledWrapper>
}

CSS Nesting

By default CSS Modules does not support nesting like Styled Components do, in this case you have to install PostCSS and PostCSS Nested plugin, it will provide similar functionality for your CSS Modules.

Please check the get started PostCSS section.