Borislav Hadzhiev
Sun Apr 24 2022·2 min read
Photo by Bianca Castillo
To use a ref to change an element's style in React:
ref
prop on the element.current
property on the ref.ref.current.style.backgroundColor = 'green'
.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;
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.
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:
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}>Some content here</div> </div> ); }; export default App;
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.