I have a simple component Here are 2 version of it - with and without styled-components:
<div id="container"> <div id="kid"></div> </div> #container { width: 100px; height: 100px; } #kid { width: 20px; height: 20px; } #container:hover #kid{ background: green; }
const Container = styled.div` width: 100px; height: 100px; `; const Kid = styled.div` width: 20px; height: 20px; `; <Container> <Kid /> </Container
How to implement the same on hover behaviour that was in the previous example?
Use React API cloneElement() type, props, children) , so basically we can't change anything of it. By cloneElement() , we can recreate the children with new props. To change the style, we can pass in a style prop into the image and also we can add an onClick handler to change the gallery state.
We can pass in refs to a styled component to access the DOM properties and methods for the given styled component. In the code above, we created a styled input called Input . Then we passed in a ref created with the useRef hook to Input . Then in the useEffect callback, we call inputRef.
Passed propsIf the styled target is a simple element (e.g. styled.div), styled-components passes through any known HTML attribute to the DOM. If it is a custom React component (e.g. styled(MyComponent)), styled-components passes through all props.
As of styled-components v2 you can interpolate other styled components to refer to their automatically generated class names. In your case you'll probably want to do something like this:
const Container = styled.div` &:hover ${Kid} { display: none; } `
See the documentation for more information!
This is copy and pasted from my answer here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With