Is it possible to apply a few styles of properties at once?
const Button = styled.div`
color: blue;
opacity: 0.6;
background-color: #ccc;
`
I need to pass active property, which will affect color, opacity, background-color. How can I apply styles for the active button at once instead of declaring conditions for each property?
const Button = styled.div`
color: ${props.active ? 'green' : 'blue'};
opacity: ${props.active ? 1 : 0.6};
background-color: : ${props.active ? 'white' : '#ccc'};
A common approach is a conditional rendering of CSS blocks with css
API:
const first = css`
color: green;
opacity: 1;
background-color: white;
`;
const second = css`
color: blue;
opacity: 0.6;
background-color: #ccc;
`;
const Button = styled.div`
${({ active }) => (active ? first : second)}
`;
const App = () => {
const [active, trigger] = useReducer(p => !p, false);
return (
<Button active={active} onClick={() => trigger()}>
Press Me
</Button>
);
};
Or using common utilities 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: LightBlue;
`,
dark: css`
color: DarkBlue;
`
}, css`color: black;`)}
`;
<Button size="large" theme={{ kind: "light" }} />
Create two classes and switch that classes according to property active
For example -
CSS
.activeClass{
color: green;
opacity: 1 ;
background-color:white;
}
.inactiveClass{
color: blue;
opacity: 0.6;
background-color: #ccc;
}
in Render
<button id="mybtn" className={this.props.active ? 'activeClass' : 'inactiveClass'} >mybutton</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.