Conditional styles with Emotion's css prop

My team uses Emotion's css prop extensively in our code base. We also like to keep our styles in a separate file, similar to CSS Modules. For developers new to Emotion or CSS-in-JS in general, it isn't always obvious how to implement conditional styling with this setup.

A simple component#

Consider this <SimpleComponent />

I am a simple component.
/* SimpleComponent.tsx */
import styles from './SimpleComponent.styles';

const SimpleComponent = () => <div css={styles}>I am a simple component.</div>;

export default SimpleComponent;
/* SimpleComponent.styles.tsx */
import { css } from '@emotion/core';

const styles = css`
  border: solid 1px #fff;
  border-radius: 10px;
  padding: 16px;
`;

export default styles;

A conditional component#

Now let's enhance the component with conditional styles.

Click here to change styles.
/* ConditionalComponent.tsx */
import { useState } from 'react';
import styles from './ConditionalComponent.styles';

const ConditionalComponent = () => {
  const [isSelected, setIsSelected] = useState(false);
  return (
    <div css={styles({ isSelected })} onClick={() => setIsSelected(!isSelected)}>
      Click here to change styles.
    </div>
  );
};

export default ConditionalComponent;
/* ConditionalComponent.styles.tsx */
import { css } from '@emotion/core';

const styles = ({ isSelected }) => css`
  border: solid 1px #fff;
  border-radius: 10px;
  padding: 16px;
  cursor: pointer;
  ${isSelected === true &&
  `
    background-color: #413F42;
    color: white;
  `}
`;

export default styles;

With a theme#

If you are using Emotion's theming capability, you can also conditionally apply theme styles.

/* ConditionalComponent.tsx */
return <div css={theme => styles(theme, { isSelected })}>
/* ConditionalComponent.styles.tsx */
const styles = (theme, { isSelected }) => css`
  ${isSelected === true &&
  `
    background-color: ${theme.colors.white};
  `}
`;

Have a better suggestion? Find me on Twitter and let me know!

A newsletter for curious developers

Join me on the fantastic journey of software development. JavaScript, CSS, HTML, React, Next.js, Flutter, GraphQL, Fauna.