DEV Community

Cover image for Toggle Password Visibility Using React useRef
Eyitayo Itunu Babatope
Eyitayo Itunu Babatope

Posted on • Edited on

Toggle Password Visibility Using React useRef

Introduction

One way to manipulate Document Object Model(DOM) without triggering a re-render of the component in React is to use the useRef hook. In this article, I will use the ref hook to toggle password input visibility.

This article is for React beginner developers with a basic understanding of the React library. The reader will learn how to toggle password field visibility using useRef.

Outline

  • Understanding useRef
  • Application of useRef
  • Toggle password Demo
  • Conclusion

Understanding useRef

React documentation defines useRef as a hook that lets you reference a value not needed for rendering. It is a built-in hook used for accessing the DOM. It does not trigger a re-render of the component. UseRef is a top-level component. You can access the value held by useRef using its current property.

Application of useRef


import React,{useRef} from 'react';

function TogglePassword(){

    const inputRef= useRef(initialValue)

}
Enter fullscreen mode Exit fullscreen mode

In the above code example, I imported useRef from React and initialized it with an initial value. The value can be string, int, or object. To access the useRef value, I used its current property as shown below.

const refValue= inputRef.current

Enter fullscreen mode Exit fullscreen mode

Toggle password Demo

I used uesRef to access the DOM to achieve the toggle password effect. In the code example below, I set the initial value of useRef to null.

import React, { useRef, useState } from "react";
import { FaEyeSlash, FaEye } from "react-icons/fa";
function TogglePassword() {
  const inputref = useRef(null);
  const [iconState, setIcon] = useState(false);
  const handleClick = () => {
    const inputattr = inputref.current.getAttribute("type");
    inputattr === "password"
      ? inputref.current.setAttribute("type", "text")
      : inputref.current.setAttribute("type", "password");
    iconState ? setIcon(false) : setIcon(true);
  };
  let icon;
  if (iconState) {
    icon = <FaEyeSlash />;
  } else {
    icon = <FaEye />;
  }
  return (
    <>
      <div>
        <p>Email</p>
        <input type="text" id="email" />
      </div>
      <div>
        <p>Password</p>
        <input ref={inputref} type="password" id="pwd" />

        <span onClick={handleClick}>{icon}</span>
      </div>
    </>
  );
}

export default TogglePassword;
Enter fullscreen mode Exit fullscreen mode

In the code above, I initialized the iconState to false using the useState hook to track password visibility. I created a handleClick function to toggle password visibility by listening to a click event on the eye icon. In the JSX of the togglePassword component, I used inputRef to hold the reference to the password input. Next, I used the inputRef.current property to access the input type attribute. If the input type attribute was password, I set the type to 'text' and vice versa using the ternary operator. Then, I toggled iconState to true or false. Next, I declared a variable icon and was assigned an eye component or eye slash component depending on the iconState.

Conclusion

In the article, I demonstrated the usage of useRef and showed how it can access the DOM. Now, the readers should have gained a better understanding of useRef and how to use it to access the DOM.

Find this article educative, comment, like, and share.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series