Style
/ Guides
Style
/ Guides

Responsive Values

In this guide, we'll explore how to use responsive values.

Creating a Renderer

First of all, we need to create our renderer and make sure to pass the responsiveValuePlugin to it.

import { createRenderer, responsiveValuePlugin } from '@weser/style'

const css = createRenderer({
  plugins: [
    responsiveValuePlugin([
      '@media (min-width: 800px)',
      '@media (min-width: 1024px)',
    ]),
  ],
})

With the plugin configured, our css function already supports responsive values.
The problem is that we still get a type error when trying to pass an array to a style property.

Ideally, this would work out of the box, but due to TypeScript limitations, we need to manually tell the type system that this is allowed.

Passing Responsive Values

In order to pass responsive values, we need to use the responsiveValue function.
All this does is cast the value to the expected type.

import { responsiveValue } from '@weser/style'

const style = css({
  color: responsiveValue(['blue', , 'red']),
})

Responsive Values as Props

On its own, this pattern is not very useful. But it shines when it comes to passing responsive values as props to components. For example:

const App = (
  <Box padding={[4, , 10]} flexDirection={['column', , 'row']}>
    <Box>Hello</Box>
    <Box>World</Box>
  </Box>
)

We can achieve this by utilizing the T_ResponsiveValue type.

import { PropsWithChildren } from 'react'
import { type T_ResponsiveValue, type T_Style } from '@weser/style'
import { css } from './renderer'

type ResponsiveStyleValue<T extends keyof T_Style> = T_ResponsiveValue<
  T_Style[T]
>

type Props = {
  padding: ResponsiveStyleValue<'padding'>
  flexDirection: ResponsiveStyleValue<'flexDirection'>
}
function Box({ padding, flexDirection, children }: PropsWithChildren<Props>) {
  return (
    <div
      style={css({
        display: 'flex',
        padding: responsiveValue(padding),
        flexDirection: responsiveValue(flexDirection),
      })}>
      {children}
    </div>
  )
}
On this page