DEV Community

Cover image for Reusable Components: Overriding Styles!
John Peters
John Peters

Posted on

Reusable Components: Overriding Styles!

When we create reusable components they often have a default layout. The layout can use custom element names, classes or other types of specificity. Lets assume a class rule is used.

.gap{
  display: grid;
  grid-template-columns: 
   repeat(
    auto-fit, 
    minmax(11em, 1fr));
}
Enter fullscreen mode Exit fullscreen mode

The problem is that when we reuse this custom control in a different container, e.g. an Expander panel, we find the '.gap' class doesn't work well.

The good news is that we can inject the 'class' to use like this.

<CustomComponent 
  className='ovr' 
  width='10vw'>
</CustomComponent>
Enter fullscreen mode Exit fullscreen mode

We enabled this by creating an @Input property.

 @Input('className') 
   className = "gap";
Enter fullscreen mode Exit fullscreen mode

Notice the default value is the class we want to use by default 'gap'.

However, as shown in our custom component above, we are overriding the default value to this...

.ovr {
  display: grid;
  grid-template-columns: 
    repeat(auto-fit, 
      minmax(20em, 1fr));
}
Enter fullscreen mode Exit fullscreen mode

Here's the markup in the custom control html to accept a 'className' to inject at run time.

<div [class]='className'>
Enter fullscreen mode Exit fullscreen mode

We are binding the class attribute saying, use the value of the variable 'className'.

The native view of the custom control looks like this:

Alt Text

The reused view inside some other 'less wide' container looks like this.

Alt Text

Notice the small difference in gaps.

JWP2021 Styling Reusable Components

Top comments (0)