Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style parent component on input focus of child component in styled-components

I've seen some burdensome solutions to this problem, using refs or event handlers in React. I'm wondering if there's a solution at all in styled-components.

The code below is clearly incorrect. I'm trying to figure out the easiest way to style my parent component, when my input child component has focus. Is this possible using styled-components?

What's the best way to go about this, specifically with styled-components in mind, even if it means relying on one of the React methods mentioned above?

const Parent = () => (
  <ParentDiv>
    <Input/>
  </ParentDiv>
);


const ParentDiv = styled.div`
  background: '#FFFFFF';

  ${Input}:focus & {
    background: '#444444';
  }
`;

const Input = styled.input`
  color: #2760BC;

  &:focus{
    color: '#000000';
  }
`;
like image 542
twils0 Avatar asked Oct 14 '25 08:10

twils0


1 Answers

Check out :focus-within! I think it's exactly what you're looking for.

https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within

like image 134
hoodsy Avatar answered Oct 17 '25 02:10

hoodsy