Josh
Josh

Reputation: 575

Is there a method to pass styling props to an Emotion css`...` prop (React)?

I'm working within a very atomised structure using @emotion/react that splits components into several different files:

In the styles.ts file, I'd have something like the below:

export const ElementWrapper = css`
  border: 1px solid red
`

In the web.tsx file, I'll compile the component in a way such as below:

import { ElementProps } from './types'
import { ElementWrapper } from './styles'

export const Element = ({ children, ...rest}: PropsWithChildren<ElementProps>) => {

  return (
    <SOME_ELEMENT css={ElementWrapper} {...rest}>
      {children}
    </SOME_ELEMENT>
  )
}

Is there any way to pass styling props to the ElementWrapper component in the current setup? For example, a marginRight=false style of prop that I could access in the styles.ts file?

I attempted to pass props to the SOME_ELEMENT component, but obviously they can't be passed through. It also appears there's no way to add further props to the css property of SOME_ELEMENT.

Upvotes: 0

Views: 685

Answers (1)

Dmitriy Zhiganov
Dmitriy Zhiganov

Reputation: 1118

I suppose you could make a wrapper function.

export const ElementWrapper = ({marginRight}) => css`
  border: 1px solid red;
  margin-right: ${marginRight};
`

// ...

return (
  <SOME_ELEMENT css={ElementWrapper({marginRight: '5px'})} {...rest}>
    {children}
  </SOME_ELEMENT>
)

Upvotes: 1

Related Questions