Open In App

How to add Phone Number Input in React.js ?

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Phone Number Input in React JS includes features like country code and number validation. It is an important part when you are creating a form input with a Phone number as the input field.

Approach to Add Phone Number Input in React JS

To add our phone input we are going to use the react-phone-input-2 package. The react-phone-input-2 package helps us to integrate the phone input into our app. So first, we will install the react-phone-input-2 package and then we will add a phone input on our homepage.

Steps to create React Application

Step 1: You can create a new ReactJs project using the below command:

npx create-react-app gfg

Step 2: Move to the Project Directory

cd gfg

Step 3: Now we will install the react-phone-input-2 package using the below command

npm i react-phone-input-2

Project Structure:

The updated dependencies in package.json file will look like:

{
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-phone-input-2": "^2.15.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
}

Example: we are importing the PhoneInput component and useState hook from react. Then we are using the useState hook to store the value of the phone number. After that, we are adding our phone input using the installed package.

Javascript




// Filename - App.js
 
import React, { useState } from "react";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import "./App.css";
 
export default class PhoneInputGfg extends React.Component {
    constructor(props) {
        super(props);
        this.state = { phone: "" };
    }
    render() {
        return (
            <div className="App">
                <h1 className="geeks">GeeksforGeeks</h1>
                <h3>Phone Number Input In React JS</h3>
                <PhoneInput
                    className="number"
                    country={"us"}
                    value={this.state.phone}
                    onChange={(phone) =>
                        this.setState({ phone })
                    }
                />
            </div>
        );
    }
}


CSS




/* Filename - App.js */
 
.App {
    text-align: center;
    margin: auto;
    justify-content: center;
}
 
.geeks {
    color: green;
}
 
.number {
    width: 300px;
    margin: auto;
}


Steps to run the application: Run the below command in the terminal to run the app.

npm start

Output: This output will be visible on http://localhost:3000/ on browser window.

Peek-2023-10-17-10-38

Output gif for phone number input



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads