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 Answer
Reset to default 1Your 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;
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