Emotion: composing css fragment with dynamic props

Created on 9 Aug 2017  路  5Comments  路  Source: emotion-js/emotion

When composing a css fragment that uses props, the props won't be used.

  • emotion version: 7.0.11
  • react version: 15.6.1

Relevant code.

const color = css`
  color: ${props => props.color};
`

const padding = css`
  padding: ${props => props.padding}px;
`

const Container = styled.div`
  composes: ${color} ${padding};
`

What you did:

I was hoping that we can dynamically composes and give dynamic css behavior to a component.

What happened:

raw string value of the function appears in the css value

Maybe there is a better way to do it? Let me know.

Most helpful comment

const color = (props) => css`
  color: ${props.color};
`

const padding = (props) => css`
  padding: ${props.padding}px;
`

const Container = styled.div`
  composes: ${color} ${padding};
`

All 5 comments

If you want to do this, wrap css in a function that accepts props and interpolate the function.

const color = (props) => css`
  color: ${props.color};
`

const padding = (props) => css`
  padding: ${props.padding}px;
`

const Container = styled.div`
  composes: ${props => {
    return ${color(props)} ${padding(props)};
  }};
`

works. Thanks @mitchellhamilton

Just so you know, you don't need the extra function in the composes interpolation, you can just interpolate color and padding.

You can do this as well @dfguo.

const color = (props) => css`
  color: ${props.color};
`

const padding = (props) => css`
  padding: ${props.padding}px;
`

const Container = styled.div`
  ${color};
  ${padding};
`
const color = (props) => css`
  color: ${props.color};
`

const padding = (props) => css`
  padding: ${props.padding}px;
`

const Container = styled.div`
  composes: ${color} ${padding};
`
Was this page helpful?
0 / 5 - 0 ratings

Related issues

kentcdodds picture kentcdodds  路  3Comments

tkh44 picture tkh44  路  3Comments

MrFungusEli picture MrFungusEli  路  3Comments

mitchellhamilton picture mitchellhamilton  路  3Comments

smlmrkhlms picture smlmrkhlms  路  3Comments