How to !important inline styles in React

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

At CrowdSync we love Bootstrap, having ditched Foundation for it, but the
overzealous approach to !important does get in our way sometimes.

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!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.