Last updated: Apr 7, 2024
Reading time·2 min

To use a ref to change an element's style in React:
ref prop on the element.current property on the ref.import {useRef} from 'react'; const App = () => { const ref = useRef(null); const handleClick = () => { ref.current.style.backgroundColor = 'salmon'; ref.current.style.color = 'white'; ref.current.style.padding = '2rem'; ref.current.style.width = '300px'; }; return ( <div> <button onClick={handleClick}>Change styles</button> <br /> <br /> <div ref={ref}>bobbyhadz.com</div> </div> ); }; export default App;

We used the useRef hook to create an object that we can use to access a DOM element.
const ref = useRef();
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 div element on which we set the ref prop.const handleClick = () => { ref.current.style.backgroundColor = 'salmon'; ref.current.style.color = 'white'; ref.current.style.padding = '2rem'; ref.current.style.width = '300px'; };
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 can access the style property on the element to get an object of the element's styles.
The style property can be used to set styles on the DOM element or read the
element's existing styles.
Notice that multi-word property names are camelCased, e.g. backgroundColor.
I've also written an article on how to change the style of an element on click without using refs.
To use a ref to toggle an element's style in React:
ref prop on the element.import {useRef} from 'react'; const App = () => { const ref = useRef(); const handleClick = () => { if (ref.current.style.backgroundColor) { ref.current.style.backgroundColor = ''; ref.current.style.color = ''; } else { ref.current.style.backgroundColor = 'salmon'; ref.current.style.color = 'white'; } }; return ( <div> <button onClick={handleClick}>Change styles</button> <br /> <br /> <div ref={ref}>bobbyhadz.com</div> </div> ); }; export default App;

The button element has an onClick listener, so every time it is clicked, its
handleClick function gets invoked.
To use a ref to toggle a style, we have to check if the style is set on the element.
const handleClick = () => { if (ref.current.style.backgroundColor) { ref.current.style.backgroundColor = ''; ref.current.style.color = ''; } else { ref.current.style.backgroundColor = 'salmon'; ref.current.style.color = 'white'; } };
If the style is set, we remove it by setting its property to an empty string.
Otherwise, we set the style property to its specific value.
Notice that multi-word property names are camelCased, e.g. backgroundColor.
Try to use your IDE for auto-completion if you are unsure how a style property is spelled.
If you use TypeScript, you might get the error useRef "Object is possibly null"