As everyone knows by now, allowing users to toggle password input visibility removes friction and improves user experience. I’ll show you how to build a toggleable password input in this tutorial!
Setup/Dependencies
This article assumes you already have a React app set up with @material-ui/core 1.0.0+ and @material-ui/icons 1.0.0+ installed as dependencies. If you need help with this this, start here, then go here.
Building the Component
First, we start with our PasswordInput class component that renders a Material UI TextField.
Here we’ve got ourselves a standard password input.
It’s worth noting that I spread the component’s props onto the rendered TextField. This allows you to treat the PasswordInput component just as you would a TextField component with a type of password.
Before getting into the mask/unmask button logic, it’s important to understand that in Material UI, the TextField component is basically just a wrapper around an Input component. Since you might want to customize the underlying props of the Input , Material UI provides a prop on the TextField called InputProps that lets you pass custom props through the TextField and into the underlying Input. Make sense? It just so happens that the Input component has an important prop we need to pass to it through the TextField , called endAdornment. Here’s the code.
Take a look at lines 15–31. This gives us a nice icon embedded to the right within the input. Let’s make it actually toggle the mask.
Here we added a passwordIsMasked state property to the component and then toggle it when the eye is clicked. When the property is toggled, it triggers a rerender of the component as either password or a text input.
Styles were added to the icon to change the cursor to a pointer when the user clicks it as well.
And there you have it, we’re done!
If you found this post useful, feel free to throw some applause my way, leave a comment, or follow me on here or on social media (my Instagram is on fire lately)!
Top comments (0)