Reputation: 107
I have been trying and can not figure out how to conditionally style an nested element with styled component.
I want the h2 element can change color depends on the props beGreen
, it is ok if I style it independently, but if I try to nest in the Container and use props. It can not work, always be in black even the props value is true...
Does the props not work in nested element?
Code
const Container = styled.section`
display: flex;
alignItems: center;
& > h2 {
color: ${props=> props.beGreen ? "green" : 'black'};
}
`
function B({className}) {
const isShow = useSelector(selectIsShow)
console.log(isShow)
const dispatch = useDispatch()
const handleLogOut = () => {
dispatch(setIsShow(false))
}
return (
<Container className={className}>
{isShow && <h2 className={`${className}-title`} beGreen={isShow}>Hi Huang, welcome!</h2>}
<SignoutBtn onClick={handleLogOut}>Logout</SignoutBtn>
</Container>
)
}
Upvotes: 1
Views: 1025
Reputation: 696
You are using the "beGreen" condition in the container. But you pass "beGreen" to h2. You should pass "beGreen" to the component where you use it, that is, to the container.
In the code below, I pass beGreen to the container.
const Container = styled.section`
display: flex;
alignItems: center;
& > h2 {
color: ${props=> props.beGreen ? "green" : 'black'};
}
`
function B({className}) {
const isShow = useSelector(selectIsShow)
console.log(isShow)
const dispatch = useDispatch()
const handleLogOut = () => {
dispatch(setIsShow(false))
}
return (
<Container className={className} beGreen={isShow}>
{isShow && <h2 className={`${className}-title`}>Hi Huang, welcome!</h2>}
<SignoutBtn onClick={handleLogOut}>Logout</SignoutBtn>
</Container>
)
}
Upvotes: 2