Emotion: Easier dynamic styling blocks

Created on 2 Jul 2017  路  5Comments  路  Source: emotion-js/emotion

Not sure how this API could look or if it's even possible. But I'd love something similar to the attr CSS function for conditional block styling. I was thinking it could look something like this:

const Alert = styled('div')`
  @type (success) {
    color: green;
    border-color: green;
    &:hover {
      color: light-green;
    }
  }
  @type (error) {
    color: red;
    border-color: red;
    &:hover {
      color: dark-red;
    }
  }
`

// ...later

<Alert type="success"/>

Similar to @media, it would take @prop-name and accept a simple prop value. If it evaluates true it collects those styles and then moves on. I could see this being very useful when dealing with things like hover states and what not.

Maybe this is better just being composed somehow? If that's so, I'd love to see some demos with more advance styling situations like the above.

Also, since this isn't a part of any spec feel free to close this if you don't think it is a good fit 馃槉

Most helpful comment

I'm also looking at adding the dynamic block syntax you describe here and in #72

All 5 comments

Just noticed composes has been added. Maybe this could be the solution? Something like:

const types = {
  success: css`
    background: green;
    &:hover: {
      background: orange;
    }
  `,
  error: css`
    background: red;
    &:hover: {
      background: blue;
    }
  `,
}

const Alert = styled('div')`
  composes: ${props => types[props.type]};
  padding: 10px;
`

render(<Alert type="success" />, mountNode)

Realized this is pretty much exactly what was asked in https://github.com/tkh44/emotion/issues/72 馃槆

I like the idea you presented, but I am hesitant to add any new syntax that's not already in the css spec. This is one of the reasons we removed fragment.

I'm also looking at adding the dynamic block syntax you describe here and in #72

Awesome! I totally agree. Adding a new syntax would be weird since it's not in the spec. I think being able to do a dynamic compose would be great and allow for an elegant solution with dynamic style blocks.

closing this for #90

Was this page helpful?
0 / 5 - 0 ratings