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
CodePudding user response:
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>
);
}