Using !important with inline styles in React


Borislav Hadzhiev

Tue Apr 26 20222 min read


Photo by Ali Kazal

Using !important with inline styles in React #

To use !important with inline styles in React:

  1. Set the ref prop on the element.
  2. Pass a function to the ref prop.
  3. Use the setProperty method on the element's style object to set a property to important.
import {useState, useLayoutEffect, useRef} from 'react'; const App = () => { const [count, setCount] = useState(0); const ref = useRef(null); useLayoutEffect(() => {'display', 'block', 'important');'background-color', 'lime', 'important'); }, []); return ( <div> {/* 👇️ with ref handled in useLayoutEffect */} <h2 ref={ref}>Count: {count}</h2> {/* 👇️ with inline ref */} <h2 ref={el => { if (el) {'display', 'block', 'important');'background-color', 'lime', 'important'); } }} > Count: {count} </h2> <button onClick={() => setCount(current => current + 1)}> Increment </button> </div> ); }; export default App;

react style important

The code snippet shows 2 ways to use !important with inline styles in React.

Adding !important to an inline style is not supported by default, so we have to use a ref and set the CSS property to important programmatically.

The first example uses the useRef hook to create a ref object.

The useRef() hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

Notice that we have to access the current property on the ref object to get access to the h2 element on which we set the ref prop.

When we pass a ref prop to an element, e.g. <div ref={myRef} />, React sets the .current property of the ref object to the corresponding DOM node.

We used the setProperty method to set a new value for a property on the element's CSS style declaration object.

useLayoutEffect(() => {'display', 'block', 'important');'background-color', 'lime', 'important'); }, []);

The method takes the following 3 parameters:

  1. propertyName - the name of the CSS property we want to modify. Note that property names of multiple words must be hyphenated.
  2. value - the new value for the CSS property
  3. priority - can be set to important or empty string.
The value parameter must not contain `!important`. The priority should be passed as the third parameter to the `setProperty` method.

The useLayoutEffect hook is identical to useEffect, but fires synchronously after all DOM mutations.

The second example shows how to set a CSS property to important with an inline ref.

<h2 ref={el => { if (el) {'display', 'block', 'important');'background-color', 'lime', 'important'); } }} > Count: {count} </h2>

The function we passed to the ref prop will get called with the element, so we can use the same approach to set its properties to important.

Use the search field on my Home Page to filter through my more than 1,000 articles.