Custom Password Revealing in ReactJS using Hooks
Sometimes password reveals control comes in handy while typing passwords in the input fields but due to the cross-browser environment things don’t work perfectly.
And I faced the same thing, which definitely provoked me to code a custom function with unlimited reveals after entering the credential.
Let’s get started with coding our very own functionality and believe it’s very easy in React 16.x . I am going to use Styled Components to style the JSX with a little introduction for the same.
Additional dependencies required for this particular feature/function:-
- Styled Components
- React Icons
Starting with making a component for signing up the user as signup.js and importing the required libraries as
In the function definition create two useState Hooks, one for password field and another for confirm password namely, showPassword and showRePassword
Now, create the structure using JSX
Now, the Styled component
Here, EyeSymbol
tag will act as a span with a dynamic CSS class. Although, we’re not using any variable CSS property. So, the dynamic CSS class will be assigned once. Make sure to apply CSS between backquotes ( ` ).
Let’s use our custom tag in JSX. Since EyeSymbol
tag is a span element we will place that after each password input field and it will automatically overlap on the input field as we’ve set margin-left
the property as -10%.
Here, we are using hook showPassword
which contains a boolean value. Since it holds a boolean value we are using the ternary operation to show Eye and EyeSlash Icons as needed. Note: For confirm password field use showRePassword
hook.
Now, we gonna add a click mouse event function to EyeSymbol
tag to register the mouse clicks and in the same function, we’ll be updating our hook‘s state using setshowPassword()
. Now, code seems like
And the last thing, adding a type
attribute to the password tags in both input password fields and we will use dynamic values for both of them.
We have again used the ternary operator to change the values of type
attributes on every click over the eye icons. Initially, showPassword
hook holds a boolean value false
. On every click on the eye icon, the hook changes its state betweentrue
and false
triggering the ternary operator to return the appropriate string between text
and password
.
Full source code is hosted on Github . For any suggestions or code improve, feel free to make a PR on Github.