# Solutions For Using A Ref To Change An Element’s Style In React

This article will show you some solutions for using a Ref to change an element’s style in React. Some ways to do it will be mentioned as using event method or using the useEffect() method.

## Using a Ref to change an element’s style in React

useRef hook is a function that returns an object with the current property initialized via the passed parameter. This returned object can be mutated and persist for the component’s lifetime.

Syntax:

const refContainer = useRef(initialValue);

Parameter: None

Two main reasons we would use useRef are accessing DOM nodes or React elements and storing a mutable variable.

### Use the event method

In this way, we will use the event method to set the inline style value for the element. For example, in the code below:

import { useRef } from "react";

export default function App() {
const ref=useRef(null);
const onClick=()=>{
ref.current.style.backgroundColor = "red";
}
return (
<>
<h2>Using a Ref to change an Element's style in React | LearnShareIT</h2>
<div ref={ref} style={{width:"100px",height:"100px"}}></div>
<br/>
<button onClick={onClick}>Change style&lt;</button>
</>
);
}

Output:

After we declare and configure the useRef hook and assign it to the ref attribute of the element we need to style, the “ref” is returned as an object with all the properties inside that div element.

We will then catch the button’s onClick event so we can reset the element’s background color by accessing ref.current.style. And we can use a Ref to change an element’s style by pressing the Change style button.

### Use the useEffect() method

Using the useEffect() hook, we will also configure the useRef for the element as above, but we will change the way to reset the style of the element by we will change them when the component is mounted in the useEffect() hook. See the example below to understand more about it.

Code:

import { useEffect, useRef } from "react";

export default function App() {
const ref = useRef(null);

useEffect(() => {
ref.current.style.backgroundColor = "red";
});

return (
<>
<h2>Using a Ref to change an Element's style in React | LearnShareIT</h2>
<div ref={ref} style={{ width: "100px", height: "100px" }}></div>
</>
);
}

The return value is still the same as above when we will change the inline style as soon as it appears. Or you can change its value by assigning the background color with a useState and replacing it with dependencies of useEffect(), reference, and code good luck.

## Summary

To summarize, we have gone through two ways for using a Ref to change an Element’s style in React with the same thing in common we all use ref.current.style. However, I recommend using the event to change it more dynamically.

Maybe you are interested: