How to !important inline styles in React

March 22, 2018

If you’ve ever used Bootstrap, you probably know that it’s pretty aggressive in it’s use of !important in it’s styles.

Similar to our post earlier in the week, the need to use !important as part of an inline style stemmed from having an arbitrary value from users that needed to be applied to an element that was using a Bootstrap style that was already using !important.

The best way to do this (outside of refactoring our code to not use the Bootstrap style) was to include the !important flag as part of the style property of the component.

Things were easy enough prior to React 15 as you could just include !important as part of your property’s value. For React 15+ that method just won’t work :(

Fortunately, you can set the property directly with JavaScript as part of the component’s reference property! It’s a bit more work, but it gets the job done:

const color = '#467db0';

return (
  <div
    className="bg-dark"
    ref={(el) => {
      if (el) {
        el.style.setProperty('background-color', color, 'important');
      }
    }}
  />
);

Now the property being assigned will be flagged as !important!

Ready to Start Being More Productive?

or get started with your email address