Single Source of Truth: Cross-Component Styling with React Compound Pattern

When building UI components, Its pretty common that we wanna trigger effects on component based on events on parent component, such as hovering. While applying style to components is straightforward, cross-component styling can become messy without proper control. The Blog explore an elegant solution using Compound Pattern to tackle the contextual styling challenge. Styling is Simple Applying a hover effect to a Button is fairly simple, A pure CSS solution is more than enough. .Button { background-color: transparent; &:hover { background-color: gray; } } The Challenge: Cross-Component Hover Effect What if we want to trigger styling transition when hovering on a parent component? Let's say a Card. The intuitive solution is to let the parent component apply extra style to the Button. There are multiple ways to implement this, just mention a few of them: Pass extra style or className props to the Button. Use in the @import syntax to reference .Button styles if using CSS modules. Reference the component directly as [${Button}]: {...} if using any CSS-in-JS solutions. I will use CSS module as example for my personal perference

May 3, 2025 - 03:56
 0
Single Source of Truth: Cross-Component Styling with React Compound Pattern

When building UI components, Its pretty common that we wanna trigger effects on component based on events on parent component, such as hovering. While applying style to components is straightforward, cross-component styling can become messy without proper control. The Blog explore an elegant solution using Compound Pattern to tackle the contextual styling challenge.

Styling is Simple

Applying a hover effect to a Button is fairly simple, A pure CSS solution is more than enough.

.Button {
  background-color: transparent;
  &:hover {
    background-color: gray;
  }
}

The Challenge: Cross-Component Hover Effect

What if we want to trigger styling transition when hovering on a parent component? Let's say a Card. The intuitive solution is to let the parent component apply extra style to the Button.

There are multiple ways to implement this, just mention a few of them:

  • Pass extra style or className props to the Button.
  • Use in the @import syntax to reference .Button styles if using CSS modules.
  • Reference the component directly as [${Button}]: {...} if using any CSS-in-JS solutions.

I will use CSS module as example for my personal perference