Search code examples
emotion-js

How to check a prop to output a block of code on a styled object in Emotion


What is the best practice to output a block of code on a styled object in Emotion?

A simple boolean statement looks like this:

const StyledComponent = styled('div')(({ check }) => ({
    position: check ? 'relative' : undefined
})

But what is the best solution for a block of code like the following example if I don't want to check each line of code?

const StyledComponent = styled('div')(({ check }) => ({
  // some style here
  // ...

  // only load pseud element if "check" is true
  '&::before': {
    content: `''`,
    position: 'absolute',
    left: '0%',
    top: '0%',
    width: '100%',
    height: '100%',
    background: 'blue'
  }
}))

I have some solutions in mind.

  • Add the if statement on the content: as without content the rest won't show. It is not my favourite because the rest of the code still getting loaded.
  • Add the if statement to load a new div inside this component. This way I can target this specific div instead of using the pseudo-class before.

Solution

  • I gave it some thought and got to this solution:

    const StyledComponent = styled('div')(
      {
        // some style here
        position: 'relative'
      },
      
      ({ check }) =>
        // only load pseudo element if "check" is true
        check
          ? {
              '&::before': {
                content: `''`,
                position: 'absolute',
                left: '0%',
                top: '0%',
                width: '100%',
                height: '100%'
              }
            }
          : undefined
    )