Borislav Hadzhiev
Tue Apr 26 2022·2 min read
Photo by Ali Kazal
To use !important with inline styles in React:
ref
prop on the element.ref
prop.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(() => { ref.current.style.setProperty('display', 'block', 'important'); ref.current.style.setProperty('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) { el.style.setProperty('display', 'block', 'important'); el.style.setProperty('background-color', 'lime', 'important'); } }} > Count: {count} </h2> <button onClick={() => setCount(current => current + 1)}> Increment </button> </div> ); }; export default App;
The code snippet shows 2 ways to use !important with inline styles in React.
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.
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(() => { ref.current.style.setProperty('display', 'block', 'important'); ref.current.style.setProperty('background-color', 'lime', 'important'); }, []);
The method takes the following 3 parameters:
propertyName
- the name of the CSS property we want to modify. Note that
property names of multiple words must be hyphenated.value
- the new value for the CSS propertypriority
- can be set to important
or empty string.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) { el.style.setProperty('display', 'block', 'important'); el.style.setProperty('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
.