Share:

R

Rupali Yadav

in

react

Sept 30, 2022

How to use ref to style in react

In this article we are going to see how to style in react using useRef hook. So, let's dive in.

We are going to create a Card component and our goal is to change the card's color when clicked on it.
We are going to use emotionJs to style our component.

1. Imports

Import css from emotion and useRef from react as shown below.

LOADING!


2. Declare a ref

Create a component with name Card and declare a ref as shown below.

LOADING!


3. Pass the ref

When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

const node = this.cardRef.current

so let's pass this ref to the the Card.

LOADING!


3. Add onClick

We are going to write the logic to change style of the card inside onClick. As seen below, we are going to point to the current property of the ref that holds the reference to the card whose background color we want to change on it's click.

LOADING!


And that's it we have successfully implemented useRef hook to update style.
 style using ref in ReactJs | Rupali Yadav
Thanks for reading with us till here 🙂
Hope you enjoyed this article! 🙂. If this article helped you please follow me on github and linkedIn for more such articles and other updates.
Please feel free to write any questions or further thoughts on this topic below.

More from Author

A Complete Guide for Making API Calls in React Using Fetch and Axios with useEffect
A Complete Guide for Making API Calls in React Using Fetch and Axios with useEffect
How to fix error: Can't perform a React state update on an unmounted component
How to fix error: Can't perform a React state update on an unmounted component
Class Components vs. Functional Components in React
Class Components vs. Functional Components in React

Share:

Copyright © 2023 Web Expe

Privacy PolicyTerms and Conditions