1fb69f117379804f644a
·2 min read

Customizing Parent Style from a Child Component in React

react
css
hooks
4d5fd787ac74e0caa4f7

Sohan R. Emon

Developer, Learner, Tech Enthusiast

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:

tsx
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?

  1. What is ref?

    • ref is a React prop that allows you to access a DOM element after it is mounted (added to the DOM).
  2. When Does It Run?

    • The ref function runs when the DOM element is attached.

This approach is quick and works for specific use cases where you need to make minor adjustments to parent styles from a child component.

Found this useful?