Learn useRef hook and how to use ref to style in react | React Hooks.

ReactRupali Yadav30 Sept 20222 min read

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.

    /** @jsxImportSource @emotion/react */ import { css } from "@emotion/react"; import { useRef } from "react";
  2. 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;
  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.

    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;
  4. 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.

 style using ref in ReactJs | Rupali Yadav
ref
useRef
hook
javaScript
reactjs
useref
style using useref
style with uncontrolled components

Share on:

Support Us:

Buy Me A Coffee