A popular method involves conditionally rendering CSS blocks using the css
API:
const first = css`
color: red;
opacity: 1;
background-color: yellow;
`;
const second = css`
color: purple;
opacity: 0.5;
background-color: #f0f0f0;
`;
const Box = styled.div`
${({ active }) => (active ? first : second)}
`;
const Section = () => {
const [active, toggle] = useReducer(p => !p, false);
return (
<Box active={active} onClick={() => toggle()}>
Click Me
</Box>
);
};
https://codesandbox.io/s/damp-sky-93y2d?fontsize=14&hidenavigation=1&theme=dark
Another option is to utilize common tools like swithProp
from styled-tools
:
import styled, { css } from "styled-components";
import { switchProp, prop } from "styled-tools";
const Button = styled.button`
font-size: ${switchProp(prop("size", "medium"), {
small: prop("theme.sizes.sm", "12px"),
medium: prop("theme.sizes.md", "16px"),
large: prop("theme.sizes.lg", "20px")
}, prop("theme.sizes.md", "16px"))};
${switchProp("theme.kind", {
light: css`
color: LightGreen;
`,
dark: css`
color: DarkGreen;
`
}, css`color: white;`)}
`;
<Button size="large" theme={{ kind: "light" }} />