Search code examples
reactjsemotion

How to add conditional styles in emotion/react?


I'm using react and emotion. I need to change the style of an element according to a boolean value. The below code does not work. How can I combine multiple styles correctly?

import { css } from "@emotion/react"

const navSticky = css({
  transform: "translateY(-10px)",
})
const navStyle = css({
  background: "red",
})

... 

 <nav css={isSticky ? {...navStyle, ...navSticky} : navStyle}> </nav>

Solution

  • As first variant i suggest use styled component for this. Set background as base property and set transform if isSticky prop has been passed with true value.

    As second variant i suggest correct your example. Use JSX Pragma with jsx function from '@emotion/react'. This allow use css prop. Docs: https://emotion.sh/docs/css-prop#jsx-pragma

    // first variant
    
    const Nav = styled.nav`
      background: red;
      transform: ${p => p.isSticky && "translateY(-10px)"};
    `
    
    const App = () => <Nav isSticky={true}>Some Elements</Nav>
    
    // second variant
    
    /** @jsx jsx */
    import {jsx} from '@emotion/react'
    
    const navSticky = {
      transform: 'translateY(-10px)',
    }
    
    const navStyle = {
      background: 'red',
    }
    
    const App = () => (
      <nav css={{...navStyle, ...(isSticky && navSticky)}}>Some Elements</nav>
    )