facepaint icon indicating copy to clipboard operation
facepaint copied to clipboard

Styled-Component Object Notation Example

Open jvanderen1 opened this issue 4 years ago • 1 comments

I would like to use facepaint inside an object, but I am not sure this is possible.

Something like:

const mq = facepaint([
  '@media(min-width: 420px)',
])
const Container = styled.div({
  ...mq({
    color: ['#f2f', '#00ff00'],
  }),
})

Is this not possible?

jvanderen1 avatar Aug 11 '21 20:08 jvanderen1

mq({ color: ['#f2f', '#00ff00'] }) will actually return an array of objects, each with the values assigned for the breakpoints.

mq({ color: ['#f2f', '#00ff00'] });

// Output
[
  {
    "color": "#f2f",
      "@media only screen and (min-width: 420px)": {
        "color": "#00ff00"
      }
  }
]

This means when you're actually spreading the array into the object which isn't what you want.

const Container = styled.div({
  ...mq({
    color: ['#f2f', '#00ff00'],
  }),
})

// Result
const Container = styled.div({
  0: {
    "color": "#f2f",
      "@media only screen and (min-width: 420px)": {
        "color": "#00ff00"
      }
  },
})

Instead, you probably want to spread the resulting object from each entry in the array to the final object. Something like this should work:

const Container = styled.div({
  ...mq({
    color: ['#f2f', '#00ff00'],
  }).reduce((acc, val) => ({ ...acc, ...val }), {}),
})

craig-jennings avatar Apr 29 '22 20:04 craig-jennings