Using a Ref to change an Element's style in React

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Photo from Unsplash

Using a Ref to change an Element's style in React #

To use a ref to change an element's style in React:

  1. Set the ref prop on the element.
  2. Get access to the element via the current property on the ref.
  3. Update the element's style, e.g. ref.current.style.backgroundColor = 'green'.
App.js
import {useRef} from 'react'; const App = () => { const ref = useRef(); 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}>Some content here</div> </div> ); }; export default App;

react set ref style

We used the useRef hook to create an object that we can use to access a DOM element.

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 div 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 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.

To use a ref to toggle an element's style in React:

  1. Set the ref prop on the element.
  2. Check if the specific style exists on the element.
  3. If the style is set, remove it. Otherwise set the style on the element.
App.js
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}>Some content here</div> </div> ); }; export default App;

react toggle ref style

To use a ref to toggle a style, we have to check if the style is set on the element.

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.