I want to change background and text color of selected component.
I used styled component and created isSelected but, don't know how to use isSelected
to change background and text color.
How to toggle it's value?
I have component like:
const Container = styled.div`
width: auto;
cursor: pointer;
:hover {
background-color: #ccc;
border-radius: 5px;
}
${({ isSelected }) =>
isSelected &&
`
background-color: #b4b4b4`}
`;
const SomeText = styled.span`
color: #000000
${({ isSelected }) =>
isSelected &&
`
color: #ffffff`}
`;
const MessageRoom = ({ item, onClick }) => {
return (
<Container onClick={onClick}>
<SomeText>{item.text}</SomeText>
</Container>
)
};
And above component is list item and following is parent component like:
return (
<div>
{list.map(item => {
return <MessageRoom item={item} key={item.id} onClick={onItemClick}/>;
})}
</div>
);
Any help would be greatly appreciated.
Edit:
const MessageRoom = ({ item, onClick }) => {
const [isSelected, setIsSelected] = useState(false);
return (
<Container isSelected={isSelected} onClick={onClick}>
<SomeText isSelected={isSelected}>{item.text}</SomeText>
</Container>
)
};
The styled components are otherwise just fine, but SomeText
is just missing a semicolon:
const SomeText = styled.span`
color: #000000;
/* ^^ */
${({ isSelected }) => isSelected && `color: #ffffff`}
`;
Since the style applied if isSelected
is true doesn't use any variables, you can also change the backticks into normal quotes:
const SomeText = styled.span`
color: #000000;
/* ^^ */
${({ isSelected }) => isSelected && "color: #ffffff"}
`;
Same applies to Container
.
To toggle the styles, you just need to pass isSelected
as a prop to SomeText
and Container
, e.g.
const MessageRoom = ({ item, onClick }) => {
return (
<Container isSelected={true} onClick={onClick}>
<SomeText isSelected={true}>{item.text}</SomeText>
</Container>
);
};
How you compute the value for isSelected
is on you.