Sept 30, 2022
How to use ref to style in react
#style using useref
#style with uncontrolled components
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. ImportsImport css from emotion and useRef from react as shown below.
2. Declare a refCreate a component with name Card and declare a ref as shown below.
3. Pass the refWhen 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.currentso let's pass this ref to the the Card.
3. Add onClickWe 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.
And that's it we have successfully implemented useRef hook to update style.
If you have any queries please write them below.