How to select multiple components at once with Emotion?

Viewed 40

I have the following styled elements:

const LogoSide = styled.div``
const NavSide = styled.p``
const Nav = styled.nav`
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;

  ${LogoSide} {
    width: 200px; // <-- How to combine those ?
  };
  ${NavSide} {
    width: 200px; // <-- How to combine those ?
  }
`

And I would like to be able to use the same CSS properties for multiple elements, something like this :

const Nav = styled.nav`
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;

  ${LogoSide} ${NavSide} {
    width: 200px;
  };
`

Is there a way to achieve this ?
I looked at the docs but could not find what i'm looking for.

2 Answers

Just put a comma between the components and it will work. You won't find it in the documentation is works just like in plain CSS when you combine classes. But for correct work you need to use Macro.

All of Emotion's Babel Macros are available by adding /macro to the end of the import you'd normally use. Docs

import styled from "@emotion/styled/macro";

const NavSide = styled.p`
  border: 2px solid red;
`;

const LogoSide = styled.div`
  border: 2px solid red;
`;

const Nav = styled.nav`
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;
  ${LogoSide}, ${NavSide} {
    width: 200px;
  }
`;

Edit dazziling-code

You can use the css prop to help with creating reusable, composable styles.

Note that you'll need to configure the JSX import source using this technique, so be sure to read the documentation I linked above.

If you're using create-react-app, and you don't feel confident after reading the docs, then you can probably just add /** @jsxImportSource @emotion/react */ at the top of each of your modules which have components that use the prop to take care of it.

Using it is pretty straightforward:

/** @jsxImportSource @emotion/react */

import {css} from '@emotion/react';

// Use this in any element's `css` prop:
const bold = css`
  font-weight: bold;
`;

const red = css`
  color: red;
`;

const boldRedUppercase = css`
  ${bold};
  ${red};
  text-transform: uppercase;
`;

export function Component () {
  return (
    <p>
      <span css={bold}>This</span> is bold and <span css={[bold, red]}>this</span> is bold red, and <span css={boldRedUppercase}>this</span> is bold red uppercase!
    </p>
  );
}

Related