I have a react component structured like this -
const MyComponent = () => (
<ContainerSection>
<DeleteButtonContainer>
<Button
theme="plain"
autoWidth
onClick={() => {
onDeleteClick();
}}
>
Delete
</Button>
</DeleteButtonContainer>
</ContainerSection>
);
I am trying to display the DeleteButtonContainer
only when the user hovers over the ContainerSection
. Both are implemented as styled-components
. Although I searched for ways to achieve this using just CSS (utilizing the hover state of the parent within the child), I could not find a solution. As an alternative, I added a state like so -
const MyComponent = ()=>{
const [isHoveredState, setHoveredState] = useState<boolean>(false);
return (<ContainerSection onMouseEnter={() => setHoveredState(true)} onMouseLeave={() => setHoveredState(false)}>
<DeleteButtonContainer style={{ display: isHoveredState ? 'block' : 'none' }}>
<Button
theme="plain"
autoWidth
disabled={!isHoveredState}
onClick={() => {
onDeleteClick();
}}
>
Delete
</Button>
</DeleteButtonContainer>
</ContainerSection>)
};
Now, my goal is to have the DeleteButtonContainer
always visible on mobile devices where hovering may not be possible. While additional JavaScript can address this, I prefer a CSS-based solution and ideally would like to eliminate the need for state entirely.
Is there a way to accomplish this using styled components without custom JS?