There might be scenarios where a child component needs to customize the style of its parent element. You can achieve it using a ref. A ref is simply a function in React that allows you to access a DOM element when it is attached to the DOM.
It's important to note that directly modifying the style of a parent component from a child is not possible through standard CSS. While the :has()
CSS selector can conditionally style a parent based on a child, it must still be applied from the parent component itself, not the child.
Hereโs a practical example where a child component removes padding from its parent element:
const Child = () => {
return (
<div
ref={(childElement) => {
if (childElement) {
childElement.parentElement!.style.padding = "0"; // Remove padding from the parent
}
}}
>
I am the child
</div>
);
};
const Parent = () => {
return (
<div style={{ padding: "20px", border: "1px solid black" }}>
<Child />
</div>
);
};
How Does This Work?
-
What is
ref
?-
ref
is a React prop that allows you to access a DOM element after it is mounted (added to the DOM).
-
-
When Does It Run?
- The
ref
function runs when the DOM element is attached.
- The
This approach is quick and works for specific use cases where you need to make minor adjustments to parent styles from a child component.
Top comments (0)