Thursday, November 28, 2024
Google search engine
HomeLanguagesHow to add Phone Number Input in React.js ?

How to add Phone Number Input in React.js ?

In this article, we are going to learn how we can add phone input in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies.

Approach: 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 in our app. So first, we will install the react-phone-input-2 package and then we will add a phone input on our homepage.

Create ReactJs Application: You can create a new ReactJs project using the below command:

npx create-react-app gfg

Install the required package: Now we will install the react-phone-input-2 package using the below command:

npm i react-phone-input-2

Project Structure: It will look like this.

Adding the Phone Input: After installing the package we can easily add a phone input on any page in our app. For this example, we are going to add a phone input to our homepage.

Add the below content in the App.js file:

Javascript




import React, { useState } from "react";
import PhoneInput from 'react-phone-input-2'
import 'react-phone-input-2/lib/style.css'
 
export default class PhoneInputGfg extends React.Component {
    constructor(props) {
        super(props);
        this.state = { phone: "" };
    }
    render() {
        return (
            <div>
                <h1>ReactJs Phone Input - neveropen</h1>
                <PhoneInput
                    country={'us'}
                    value={this.state.phone}
                    onChange={phone => this.setState({ phone })}
                />
            </div>
        );
    }
};


Explanation: In the above example first, 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.

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

npm start

Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments