i want to add a background color to the styled component div if state active is true.
i am doing it like so
function Main() {
const [active, setActive] = useState(false);
return (
<ChildComponent
active={active}/>
);
}
const ChildComponent = styled.div<{ active?: boolean }>`
height: 100%;
${({ active }) => active && 'background-color: grey';}
`;
This works fine. but instead of just passing string grey to background color i want to pass props like below.
const ChildComponent = styled.div<{ active?: boolean }>`
height: 100%;
${({ active }) => active && 'background-color:'${(props: any) =>
props.theme.colors.grey.light3}};
`;
This is not the right syntax to do it. could someone help me fix this thanks.
You can nest template literals within template literals as long as they're located inside an interpolated expression block ( ${...}
).
So your code should look like this:
const ChildComponent = styled.div<{ active?: boolean }>`
height: 100%;
${({ active, ...props }) => active && `background-color: ${(props: any) =>
props.theme.colors.grey.light3}`};
`;
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.