React Forms with React Hooks with Password Show/Hide functionality.

In this tutorial lets see how we can create a React form with React Hooks with the functionality showing and hiding passwords without any external react-form npm packages.

The final working prototype we are gonna achieve.

chrome-capture (3)

If you want to know how to get started in react see my previous article Creating a new react app.

We are going to use two Hooks for our React forms.

1. useState.

2. useRef.

First I will give a brief intro to these two hooks ( After this tutorial, I will be making detailed analysis of which React Hook I have been using in name of React Hooks series).

useState:

With introduction of React Hooks we can easily change state with useState hook. Before that we had to use a lot of code to just initialize a State in a Class Component.

Syntax:

const[state,setState]=useState();

useRef:

Before React Hooks was created, we had to use React.createRef and access the DOM elements and manipulate them. With useRef, it is very easy to do the above step.

Syntax:

const password = useRef();
const changetype = () => {

password.current.type="password"

} 
<input type ="text" onClick={changetype} ref={password}></input>

Lets first import the necessary packages,

import React, {useState,useRef} from 'react';

Now we need to install font-Awesome npm package to use font-awesome icons React.js.

In simple Html, CSS webpage we would get the script tag from font-awesome website and place it in head tag and use in body tag to use font-awesome.

In React we have to install font-awesome npm packages to do that.

Copy and Paste the below code in terminal to install the font-awesome npm packages.

npm i --save @fortawesome/fontawesome-svg-core
npm install --save @fortawesome/free-solid-svg-icons
npm install --save @fortawesome/react-fontawesome

So lets get into form handling in React.js.

We create a functional component in react.js and add the necessary code in it.

const Form  = () =>{
    return (
        <div>
            <form onSubmit={submit}>

<div className="grid">
<div>
<input type = "email" value={email} name="email" onChange={change}></input>
</div>
<div>
<input type = "password" value={password} name="password" onChange={change}></input>
</div>
<div>
<input type = "submit"  name="submit" ></input>
</div>
</div>

            </form>
        </div>
    )
}

Now lets define change and submit function in react.js,

  • We create a useState hook of Object type with email and password and destructure it.
  • Then we define the ‘change’ function by setting the names of html tags to its values. Make sure the name and value are same as below.

<input type = "email" value={email} name="email" onChange={change}></input>

  • We use the spread operator to keep the existing elements in the object.
  • Whenever the input value is changed ‘change’ function is triggered.
  • After that we use a key of array of [e.target.name] to set the given input values to the useState’s object key-value pair.
  • After these steps, the submit function is defined such that the default action of submit button (which is when the submit button is clicked the page reloads) is removed and state is being cleared for UX purposes.

In submit function you can/have to implement backend logic with Axios/fetch of your own.


const [formdata,setformdata]=useState({


email:'',
password:'',


})

const {
email,
password,
} = formdata;


const change=(e)=>{

setformdata({...formdata,[e.target.name]:e.target.value})

}
const submit = e =>{

    e.preventDefault();
    // Submit to backend API with Axios/fetch 
    // Implement your backend logic here. 

setformdata({


email:'',
password:''



})

}

Now in

<input type = "password" value={password} name="password" onChange={change}></input>

We add the functionality of show/hide password.

In your react file, include the following code which contain font-awesome packages,


import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

import { faEye,faEyeSlash } from "@fortawesome/free-solid-svg-
icons";

const Eye = <FontAwesomeIcon className="icon" icon={faEye} />;

const EyeSlash = <FontAwesomeIcon className="icon" icon ={faEyeSlash}/>;


Add a useState and useRef hook above change and submit function.



const[show,setshow]=useState(false)
const pass = useRef();

In Submit function make the below changes.

const submit = e =>{

e.preventDefault();

setformdata({
name:”,
email:”,
password:”
})

//New code added below

setshow(false)

}

Now make some changes to the password input like below,

<div className="eye">

<input ref={pass} type = "password" placeholder="Enter Password"value={password} name="password" onChange={change}></input>

{show ? <i onClick={showpassword}>{Eye}</i>:<i onClick={showpassword}>{EyeSlash}</i>}

</div>

Now lets add the code which really does the job,

The below code will fire when the eye button is being clicked.
When the page first loads it will remain as a password type attribute.

But when we click on the eye button, its type will change to text attribute. Now the text are visible.

The input’s type attribute is changed with help of useRef’s .current property.

It is as same e.target., but with help of react hooks.

We can change the value, type, name and all other html attribute associated with that html tag with useRef’s .current property.

So for now we are going to change the attribute of the input[type=”password”] from password to text when the eye button is clicked and vice versa.

Then, the eye button becomes slashed when we click on it and this is done with React’s useState hook.

We at first, set it as false and then when we click the eye button, the state is changed from false to true and vice versa.

So add the onClick ‘showpassword’ function code as below.

const showpassword = () =>{

setshow(!show)
pass.current.type = show ? 'password':'text';

}

And thats it, We have created a simple, yet effective React form with show/hide functionality.

Here is the CSS code used.

@import url("https://fonts.googleapis.com/css2?family=Ovo&display=swap");

* {
  font-family: "Ovo", serif;
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

.grid{
margin-top: 10%;
margin-left: 35%;
margin-right:35%;
display:flex;
flex-direction: column;
box-shadow: 0 0 6px grey;
height:65vh;

}

input{


 padding:10px; 
 width:75%;
 margin:20px;
 margin-top: 10px;
 margin-left: 10%;
font-size: 20px;


}

input:active, input:focus{
transition: 1s;
border:2px solid blue;
outline:none;
}


input[type="submit"]{

 transition: 1s;
 width:20%;
 margin-left: 35%;
 color:white;
border:none;
outline:none;
background-color: blue;
font-size: 20px;
font-weight: 600;


}

input[type="submit"]:hover{

transition: 1s;
cursor: pointer;
transform: translateY(-2px);
box-shadow: 0 0 6px red;

}

.eye{

  position: relative;
  display: flex;
  margin-bottom: 14px;

}

i {
  position: absolute;
  top: 35%;
  right: 18%;
}
i:hover {
    cursor: pointer;
}

.topic{

margin-top: 5%;
margin-bottom:5%;
margin-left: 27%;
margin-right: 23%;    
font-size: 30px;
text-decoration: underline;

}

.label{

margin-left: 10%;
margin-top: 10px;
font-size: 20px;
font-weight: 600;
}

The complete Form.js file code.




import React,{useState,useRef} from 'react'
import "./form.css"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEye,faEyeSlash } from "@fortawesome/free-solid-svg-icons";
const Eye = <FontAwesomeIcon className="icon" icon={faEye} />;
const EyeSlash = <FontAwesomeIcon className="icon" icon ={faEyeSlash}/>;

const Form = () => {

const [formdata,setformdata]=useState({

email:'',
password:'',


})

const {
email,
password,
} = formdata;

const[show,setshow]=useState(false)
const pass = useRef();

const change=(e)=>{

setformdata({...formdata,[e.target.name]:e.target.value})

}
const submit = e =>{

    e.preventDefault();


setformdata({

name:'',
email:'',
password:''



})

setshow(false)

}



const showpassword = () =>{

setshow(!show)
pass.current.type = show ? 'password':'text';

}


    return (
        <div>
            <form onSubmit={submit}>

<div className="grid">

<div className="topic">Register Form</div>
<div className="label">Email:</div>
<input type = "email" value={email} placeholder="Enter Email"name="email" onChange={change}></input>

<div className="label">Password:</div>
<div className="eye">


<input ref={pass} type = "password" placeholder="Enter Password"value={password} name="password" onChange={change}></input>

{show ? <i onClick={showpassword}>{Eye}</i>:<i onClick={showpassword}>{EyeSlash}</i>}



</div>


<div>
<input type = "submit"  name="submit" ></input>
</div>
</div>

            </form>
        </div>
    )
}

export default Form;



`

You can find the complete source code below in my github repo.

React Forms with show/hide functionality.

But still this does not have Error Handling, But in future I will add it and give a link here.

You can add upon this logic.

My Personal Experience:

This one article took a lot of time to research and execute. If you are struggling with React forms this one is for yours.

I have banged my head over the table for a lot of time to get React form with hooks right.

So take your time to master this stuff.

Forms are very essential in any website. So get hold of it with help of this article.

Thank you for reading!

If you like this article, Unicorn this one! Heart/Like this one and save it for reading it later.

My Other Articles:

Create your Web Presence with Namecheap

Leave a Comment

Your email address will not be published. Required fields are marked *