I have one component that is an input wrapped in a styled div
component and a second component that uses the first one but it should change some of the CSS style using child selectors. The first component I have is
import React from "react";
import styled from "styled-components";
const Container = styled.div`
margin: 2px 0px;
width: 100%;
flex-grow: 1;
`;
function EditInput() {
return (
<Container className="testClass">
<input />
</Container>
);
}
export { EditInput };
while the second one is
import React from "react";
import { EditInput } from "./EditInput";
import styled from "styled-components";
const EditInputs = styled(EditInput)`
div:nth-child(1) {
background: red;
}
.testClass {
background: red;
}
&:nth-child(1) {
background: red;
}
& > *:nth-child(1) {
background: red;
}
`;
export function Input() {
return <EditInputs />;
}
This returns me an input field but the child selectors' CSS does not apply changes. I tried with multiple approaches, as you can see, but none of them works. However, if I add background: red
into Container
from the first component, the color gets changed.
I prepared a sandbox here so you can check it out yourself. Do you know how can I fix this and why does this occur? Thanks in advance o/
CodePudding user response:
The styled factory depends on the classname prop being passed down.
function EditInput({ className }) {
return (
<Container className={className}>
<input />
</Container>
);
}