red house 87
red house 87

Reputation: 2415

React - using inline important styling

I'm using React in a chrome extension and I need to insert elements into the page via the content script. The extension may insert these elements into any page in which it's loaded on (kind of like Last Pass would) so I need to override any existing styling that might target general elements.

For the most part i've managed to get around this via using iframes as css in iframes can't be modified but I need to give styling to the iFrames and one or two parent containers in order for them to display properly.

As i've just learnt you unfortunately can't use the !important feature with inline React CSS. I can maybe understand why this is but for things live Chrome Extensions that use content scripts I need to be able to use important tags...

I've been looking for a work around and managed to find this:

react-with-important-style

But whenever the component renders it doesn't look very smooth at all so looking for another option.

Can anyone recommend a good workaround?

Thanks

Upvotes: 0

Views: 4897

Answers (1)

Momin Bin Shahid
Momin Bin Shahid

Reputation: 836

I can not say it is a good workaround because it uses refs (inline), but it will do the trick. You can simply insert this below snippet as an inline property as mentioned in this post

ref={(el) => {
      if (el) {
        el.style.setProperty('background-color', color, 'important');
      }
    }
}

Moreover, there is a hack for earlier versions of ReactJS, that zpao posted. i.e.

style = {
  color: 'red',
  backgroundColor: {
    value: 'blue',
    important: 'true'
  }
}

Another approach is this:

<style>{"\
i{\
float:none !important;\
}\
"}</style>

Use above code in your JSX as shown below:

 let activityStats = <table className="table" id="act-stats-user">
        <style>{"\
            i{\
              float:none !important;\
            }\
          "}</style>
        <tbody>
          ...
        </tbody>
        </table>

If nothing works, then the perfect solution to this problem is to create a custom.css file, import it and write your CSS there with !important (if it`s that important)


P.S: try to avoid using !important all the time, as it is considered to be a bad practice among the developers but occasionally it`s legal I think :).

Upvotes: 2

Related Questions