import React,{useState} from "react";
function Password(){
const [pass,setPass] = useState("password")
const handleclick =()=>{
setPass(("password")? "text" : "password")
}
return(
<div>
Password:<span style={{position:"relative"}}><input type={pass} name="" id="" />
<i onClick={handleclick} style={{position:"absolute", top:"6px" , right:"5px"}} class="fa-solid fa-eye"></i></span>
</div>
)
}
export default Password;
When i used the useState in react Js for password show and hide on icon click there are not working. I only show the password show once time but i need to show and hide it whenever click the icon
3
Answers
You should set your new state based on your previous state.
With the code that you have provided, the input type is set to
'text'
only once and it won’t work like a toggle switch, because in yourhandleClick()
you are checking a string value to set the new value.That condition always returns the same results, therefore, it won’t work like a toggle switch.
the correct code would be something like this:
This way we check the value of the previous state, if it is
'password'
we set it to'text'
, otherwise, we set it to'password'
.try this