A guide on toggling the password input type between text and hidden in a React application

I am facing an issue with toggling the input type between password and text to display the password in a login form. The expected functionality is that clicking on the eye icon next to the password input should reveal the password in plain text, but this is not happening as intended. I have attempted to dynamically switch the password input type from 'password' to 'text' without success so far. Below is the code snippet:

const [showPassword, setShowPassword] = useState(false)
const passwordRef = useRef<HTMLInputElement>(null);

const handleShowPassword = (ref: React.RefObject<HTMLInputElement>) => {
  if (ref.current && ref.current.id === 'password') {
    setShowPassword((prev) => !prev);
    if (showPassword) {
      ref.current!.type = "password";
      console.log('passwordRef.current?.type: ', ref.current?.type); // password
    } else {
      ref.current!.type = "text";
      console.log('passwordRef.current?.type: ', ref.current?.type); // text
    }
  }
};

return (

<Container>
  <BackgroundBox />
  <FormBox>
  
      {/* Password */}
      <div className='auth-input-container login-password'>
        <FaKey className="auth-icon" size='20px' />
        <input
          type="password"
          id="password"
          name="password"
          placeholder="Enter password"
          className="auth-input"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.password}
          ref={passwordRef}
        />
        {
          showPassword ? <FaEyeSlash className="auth-icon-password-eye" onClick={() => handleShowPassword(passwordRef)} />
            : <FaEye className="auth-icon-password-eye" onClick={() => handleShowPassword(passwordRef)} />
        }
      </div>
      {formik.touched.password && formik.errors.password ? (
        <div className="error-message">{formik.errors.password}</div>
      ) : null}
// and closing tags

Even though the types logged within handleShowPassword correctly show 'text' or 'password', the actual passwordRef type stubbornly remains 'text'. Strangely, when using Vanilla JS instead of refs:

const handleShowPassword = (ref: React.RefObject<HTMLInputElement>) => {
const DOMref = document.getElementById('password') as HTMLInputElement;
if (DOMref.id === 'password') {
  console.log('DOMref: ', DOMref);
  if (DOMref.type === 'password') {
    DOMref.type = 'text'
  } else {
    DOMref.type = 'password'
  }
}

};

This method works flawlessly. Why is this discrepancy occurring? How can I rectify this issue?

Answer №1

If you want to toggle between showing and hiding a password input field, you can achieve it by conditionally changing the input type like this:

const [showPassword, setShowPassword] = useState(false)

  const handleShowPassword = () => {
    setShowPassword(!showPassword);
  };

return (

<Container>
  <BackgroundBox />
  <FormBox>
  
      {/* Password */}
      <div className='auth-input-container login-password'>
        <FaKey className="auth-icon" size='20px' />
        <input
          type={showPassword ? "text" : "password"}
          id="password"
          name="password"
          placeholder="Enter password"
          className="auth-input"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.password}
          ref={passwordRef}
        />
        {
          showPassword ? <FaEyeSlash className="auth-icon-password-eye" onClick={handleShowPassword} />
            : <FaEye className="auth-icon-password-eye" onClick={handleShowPassword} />
        }
      </div>
      {formik.touched.password && formik.errors.password ? (
        <div className="error-message">{formik.errors.password}</div>
      ) : null}
// and closing tags




Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve a particular object from the state and access one of its elements?

I have a component called Tweets.js: import React, {Component} from "react"; export default class Tweets extends Component { constructor(props) { super(props); this.state = {tweets: [], users: []}; } componentDi ...

Setting up your configuration for create-react-app once you have ejected to start building your very own component library

As I embarked on creating a component library to publish on NPM and reuse in various apps, I decided to start by developing a React app with the help of create-react-app. However, it quickly became apparent that the default configuration of create-react-ap ...

The module 'crypto-js' or its corresponding type declarations cannot be located

I have a new project that involves generating and displaying "QR codes". In order to accomplish this, I needed to utilize a specific encoder function from the Crypto library. Crypto While attempting to use Crypto, I encountered the following error: Cannot ...

Creating a background with image overlays in React: A step-by-step guide

My challenge is to have an image that covers the entire background but it seems to stop abruptly where another object is placed, unable to extend further. I am utilizing Material UI and here is a snippet of my code: import { Image } from "../images&q ...

Aggregate the data chunks in the antd table into groups

I've been struggling to find a solution for this specific issue. My goal is to group the data in my table based on a particular field, but I need it to be styled as depicted in the image linked below. https://i.stack.imgur.com/OsR7J.png After looking ...

error 404 when sending a xhr request in node and react js

I am currently developing a basic login page in React that needs to connect to a database through an AJAX call to a Node.js file. Here is the Node.js code I have implemented: var express=require('express'); var app=express(); var db=require(&ap ...

Accessing PDF content in a Next.js 13 API route handler leads to a 404 error

After following a tutorial on YouTube (link here) about uploading a PDF file to an Express server and extracting its text content, I encountered an issue. My main concern is extracting the text from the PDF rather than displaying it. Everything works smo ...

Issue with Material-UI Drawer's Flexbox horizontal scrolling functionality incompatibility with iOS Safari causing problems

I have encountered an issue with scrolling horizontally inside a Drawer component from Material-UI. While it works smoothly outside of the Drawer, I am facing difficulties when trying to scroll within it. After testing it on various platforms, I found tha ...

Tips for aligning the types of objects transmitted from a Web API backend to a React/Redux frontend

After creating a backend for my app using .net, I now have CRUD operations available to me. When performing a POST action, the response includes an entire new item object: {"Id":"7575c661-a40b-4161-b535-bd332edccc71","Text":"as","CreatedAt":"2018-09-13T15 ...

Rendering a component inside an accordion that was generated within a loop using React

Seeking a clever solution for the following scenario: I have a component that generates accordion elements in a loop based on an array of data. Each accordion has the following structure: <Accordion expanded={expanded === 'panel1'} onChange={ ...

Node.js impressively stores files without file extensions

app.post('/file_upload', function (req, res) { var form = new formidable.IncomingForm(); form.uploadDir = path.join(__dirname, '/uploads'); files = [], fields = []; form.on('field', function(field, ...

Problem concerning the window object in a React functional component

Hey there, I am currently facing a situation where I need to access the window object within my React component in order to retrieve some information from the query string. Here is an excerpt of what my component code looks like: export function MyCompone ...

Creating a dropdown menu using React库

The API response I received looks like this:- [ { "Product.Name": "Data Migration - Test1", "Product.Id": "8ad0", "Product.Hello__c": { "Value": "First ...

Centering form fields in ReactJS using Material UI

I'm currently facing a challenge trying to center-align my react form. Below is the structure of my form: The technology I am using is Material UI for ReactJS <Grid item xs={12}> <Grid item xs={12}> <FormGroup ...

Component access in Next.js tailored to different user roles

I need help with implementing access restrictions to an admin area based on an integer flag called isAdmin in my users table, which can be set to either 0 or 1. Within the admin component, I have created a function to fetch a unique user from an API route ...

Tips for streamlining responses for the latest create-next-app version

After running npx create-next-app@latest, a series of questions are prompted that disrupt our docker pipeline automation. Is there a way to automate the response to these questions? Currently, we have this command in our Dockerfile: RUN npx --yes create- ...

Guide to simultaneously displaying two modals in react.js with either MUi or tailwindcss

Can anyone help me implement a modal with the same functionality as the share feature on Google docs or Google drive? I am looking for guidance on how to achieve this and if there are any examples available on CodePen or similar code sharing websites. htt ...

How to extract just the year from Material-UI's date picker in React

const displayYearOnly = (date) => { const year = date.getFullYear(); console.log(year); }; return ( <div style={{ marginRight: "20px" }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DemoContainer componen ...

Visualization of extensive datasets in JavaScript

I'm currently developing a dashboard in JS for displaying sales data plots to users. Can anyone recommend a JavaScript library that meets the following criteria: Capable of plotting a large number of points (ex: 100k or more) Interactive functional ...

Reactjs implemented with Material UI and redux form framework, featuring a password toggle functionality without relying on hooks

Currently, I am working on a react project where I have developed a form framework that wraps Material-UI around Redux Form. If you want to check out the sandbox for this project, you can find it here: https://codesandbox.io/s/romantic-pasteur-nmw92 For ...