How can I add a style to a parent component when the input gets focused with styled component?
When the Input component
gets focused, I'd like to add border style to the Container component
.
app.js
import "./styles.css";
import { Container, Input } from "./styles";
export default function App() {
return (
<Container>
<h1>Hello CodeSandbox</h1>
<Input />
</Container>
);
}
styles.js
import styled from "styled-components";
export const Input = styled.input`
width: 100px;
background-color: pink;
`;
export const Container = styled.div`
text-align: center;
width: 200px;
height: 300px;
background-color: green;
border-radius: 4px;
${Input}:focus & {
border: 5px solid #04435e;
}
`;
Is there any way that I can do this?
CodePudding user response:
You can be achieved using the :focus-within
CSS pseudo-class on the Container component.
styles.js
export const Container = styled.div`
text-align: center;
width: 200px;
height: 300px;
background-color: green;
border-radius: 4px;
&:focus-within {
border: 5px solid #04435e;
}
`;