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

6.2k Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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

And then you can use like this:

<div css={{ mb: '$40' }} />
0
On

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!

1
On

I was looking for this answer and tried a few different ways.

The easiest way for me turned out to be locally scoped theme-tokens.

So your styled component would look like this:

const Spacer = styled('div', {
    marginBottom: '$$marginSize',
});

And then pass the locally scoped token into the css prop:

<Spacer css={{ $$marginSize: '$sizes$3' }} />