Share:

R

Rupali Yadav

in

react

Sept 30, 2022

How to use ref to style in react

#ref

#useRef

#hook

#javaScript

#reactjs

#useref

#style using useref

#style with uncontrolled components

#webexpe

#webexpe.com

#rupali yadav

#rupali

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 🙂. If this article helped you please follow me on twitter, github and linkedIn for more such articles and other updates.
If you have any queries please write them below.

More from Author

What is hoisting in Javascript
What is hoisting in Javascript
Difference between pass by value and pass by reference in javascript
Difference between pass by value and pass by reference in javascript
Difference between a state and prop in react
Difference between a state and prop in react

Share:

Copyright © 2022 Web Expe

Privacy PolicyTerms and Conditions