最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

show and hide password eye icon click not working in reactJs - Stack Overflow

programmeradmin3浏览0评论

import React, { useState } from 'react';

import Eye from './Eye'; import EyeOff from './EyeOff';

function App(){

 const [password, setPassword] = useState(false);

 let hendleClick = ()=>{
      setPassword(!password)
  }


   
 return(
      <>
      

       <input type={ password ? 'password' : 'text'} 
       onChange={(e)=>{setPassword(e.target.value)}} />
      
    
      {password ? <Eye onClick={hendleClick} /> : <EyeOff onClick={hendleClick} /> }
        
       
      </>
 )

}

export default App;

import React, { useState } from 'react';

import Eye from './Eye'; import EyeOff from './EyeOff';

function App(){

 const [password, setPassword] = useState(false);

 let hendleClick = ()=>{
      setPassword(!password)
  }


   
 return(
      <>
      

       <input type={ password ? 'password' : 'text'} 
       onChange={(e)=>{setPassword(e.target.value)}} />
      
    
      {password ? <Eye onClick={hendleClick} /> : <EyeOff onClick={hendleClick} /> }
        
       
      </>
 )

}

export default App;

Share asked Feb 7 at 8:43 Kamruddin AhmadKamruddin Ahmad 14 bronze badges 1
  • 1 Is password a boolean or a string? setPassword(e.target.value) makes no sense if it's a boolean. I think you need at least 2 states – Hao Wu Commented Feb 7 at 8:58
Add a comment  | 

1 Answer 1

Reset to default 1

Your issue is that you are using the same password state for both managing the password visibility and storing the password value. This causes conflicts because password is supposed to be a boolean (true or false) for toggling visibility, but you're also setting it to a string when handling input changes.

To fix the issue use two separate state variables: one for storing the password and another (showPassword) for toggling visibility.

The corrected code

import React, { useState } from 'react';
import Eye from './Eye';
import EyeOff from './EyeOff';

function App() {
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);

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

  return (
    <>
      <input
        type={showPassword ? 'text' : 'password'}
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />

      {showPassword ? (
        <Eye onClick={handleClick} />
      ) : (
        <EyeOff onClick={handleClick} />
      )}
    </>
  );
}

export default App;
发布评论

评论列表(0)

  1. 暂无评论