Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a prop value be used in an Stitches js component?

How to pass a prop value into a Stitchesjs component and use it in the component definition?

This is a common pattern in styled-components. In Stitches, however, I can't seem to find a way. Take this component for example:

const Spacer = styled('div', {
    '16': {marginBottom: '$16'},

    variants: {
        size: {
            '20': {marginBottom: '$20'}
        }
    }
});

Instead of creating 10 variants, I want to pass the amount trough a prop:

<Spacer size={'30px'} />

or even better:

<Spacer size={'$sizes$3'} />

How can I use this value so that the marginBottom matches whatever I give it?

like image 526
Edy Bourne Avatar asked Aug 30 '25 16:08

Edy Bourne


2 Answers

There was a discussion on Stitches Github about the possibility to pass dynamic values as property. But the goal of stitches is to have the smallest runTime possible, so it was not implemented !

Github PR stitches

When you need to use a JSX variable in stitches that can be any value, one solution would be to use CSS variables;

All stitches elements get the css property, and you can pass new properties through it!

Styled component:

    export const Box = styled('div', {
    marginTop: 'var(--margin-top)',
    backgroundColor: 'red',
    width: '200px',
    height: '200px',
    })

Component:


export function Hero({props = 200 }) {

  const variableExample = `${props}px`
  return (
    <>
    <Box css={{ '--margin-top': '10px' }} />
    <Box css={{ '--margin-top': '150px' }} />
    <Box css={{ '--margin-top': variableExample }} />
    </>
  )
}

By far the best solution that has worked for me for this very problem. simplifies the code and is better to maintain later!

like image 98
Leandro Rodrigues Avatar answered Sep 02 '25 07:09

Leandro Rodrigues


Take a look at https://stitches.dev/docs/utils.

And then you can use like this:

<div css={{ mb: '$40' }} />
like image 24
Murillo de Miranda Pereira Avatar answered Sep 02 '25 07:09

Murillo de Miranda Pereira