Published on

How to Target Another Styled Component on Hover in React

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Target Another Styled Component on Hover in React

When working with styled-components in React, applying hover effects to another component can be tricky. The common use case is when hovering over a parent element, and then showing or styling a child component dynamically. Below are the best ways to handle this efficiently.

Directly Referencing Another Styled Component

In styled-components v2+, you can interpolate another styled component to reference its auto-generated class name. This is the preferred approach:

import styled from 'styled-components'

const Button = styled.button`
  display: none;
`

const Wrapper = styled.div`
  &:hover ${Button} {
    display: block;
  }
`

export default function App() {
  return (
    <Wrapper>
      <Button>Click Me</Button>
    </Wrapper>
  )
}

Using a Parent Selector for Child Elements

Another approach is to reference the parent from within the child component. This method encapsulates the styling better:

const Button = styled.button`
  ${Wrapper}:hover & {
    display: block;
  }
`

Handling Hover for Sibling Components

If you need to affect a sibling component on hover, use the general sibling selector (~):

const ContentA = styled.span`
  &:hover ~ ${ContentB} {
    opacity: 1;
  }
`

Targeting a Component with a Custom Class Name

If you're using styled-components v1, or need an alternative method, manually assigning a unique class name works:

const Wrapper = styled.div`
  &:hover .my-unique-button-class {
    display: block;
  }
`

;<Wrapper>
  <button className="my-unique-button-class">Show on Hover</button>
</Wrapper>

Using Styled Components with MUI

For Material UI users, you can apply hover styles using the & selector:

const useStyles = makeStyles({
  parentClass: {
    '&:hover $childClass': {
      display: 'flex',
    },
  },
  childClass: {
    display: 'none',
  },
})

FAQs

1. How do I target another styled component on hover in React?

Use interpolation to reference another styled component inside styled-components:

const Wrapper = styled.div`
  &:hover ${Button} {
    display: block;
  }
`

2. Can I use CSS modules instead of styled-components?

Yes, you can achieve similar results using CSS modules:

.wrapper:hover .button {
  display: block;
}

3. How do I conditionally apply styles based on props?

Use the function syntax in styled-components:

const Button = styled.button`
  ${({ isActive }) => isActive && 'background-color: blue;'}
`