Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styled-Components: specify styles of children on parents hover

I have a simple component Here are 2 version of it - with and without styled-components:

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; } 

With Styled Components

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?

like image 851
kurumkan Avatar asked Jul 11 '17 13:07

kurumkan


People also ask

How do you style a child component in React?

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.

How do you pass ref to styled components?

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.

Can you pass Props to styled component?

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.


1 Answers

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.

like image 179
mxstbr Avatar answered Sep 19 '22 11:09

mxstbr