How to make a show or hide password toggle button in Reactjs?
To show or hide the password in the input field in Reactjs, the simple logic behind this is to change the type of input attribute to text
from password
and vice versa on clicking the "Show password" button or an appropriate button of your own.
Step 1
First, let's make an simple function named Password and in this function lets create simple input tag with password
as the type of the input field as you can see below code.
Step 2
passwordShown
to determine if the password in the input field should be shown using the useState()
react hook.Let's give the initial boolean state value as
false
as we do not want the input field to be shown when the user tries to enter the password at first. We only need them to be visible as the user clicks on the Show Password
button.Step 3
password
as the type of the input tag, we need to make it dynamic so that if the passwordShown
boolean state is true
it should show the password and if it is false
it should not show the password.It can be done like this,
As you can see that in the type
attribute we are first checking if the passwordShown
boolean state is true
or false
and applying the attribute value according to it.
Step 4
Now let's make a Show Password
button and attach an onClick
handler to it so that when the user clicks the button it should show the password.
Here we have made a handler called togglePassword
so that when it is invoked it will just inverse the boolean state of passwordShown
.