Learn useRef hook and how to use ref to style in react | React Hooks.
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.
-
Imports
Import css from emotion and useRef from react as shown below.
/** @jsxImportSource @emotion/react */ import { css } from "@emotion/react"; import { useRef } from "react";
-
Declare a ref
Create a component with name Card and declare a ref as shown below.
const Card = () => { const cardRef = useRef(""); return <div>...</div>; }; export default Card;
-
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.
import { css } from "@emotion/react"; import { useRef } from "react"; const cardContainer = css` margin: 50px; `; const card = css` background: #fff; border: 1px solid #ccc; color: #000; max-width: 400px; padding: 15px 10px; `; const Card = () => { const cardRef = useRef(""); return ( <div css={cardContainer}> <button ref={cardRef} css={card}> <h1>Title</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.{" "} </p> </button> </div> ); }; export default Card;
-
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.
const Card = () => { const cardRef = useRef(""); return ( <div css={cardContainer}> <button ref={cardRef} css={card} onClick={() => { cardRef.current.style.background = "#DAF7A6"; }} > <h1>Title</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.{" "} </p> </button> </div> ); };
And that's it we have successfully implemented useRef hook to update style.