Implement Phone Input In React Js

We’ll use the react-phone-input-2 package to add our phone input. We can integrate phone input into our app with the aid of the react-phone-input-2

package. In order to add a phone input to our webpage, first we will install the react-phone-input-2 package.

By using the command listed below, you can start a new ReactJs project:

npx create-react-app gfg

Using the command below, we will now install the react-phone-input-2 package:

npm i react-phone-input-2

Once the package has been installed, adding a phone input to any page of our app is simple. We will include a phone input on our homepage for the

purposes of this demonstration.

In the App.js file, add the following text:

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 - GeeksforGeeks</h1>
        <PhoneInput
          country={'us'}
          value={this.state.phone}
          onChange={phone => this.setState({ phone })}
        />
      </div>
    );
  }
};

First, we are importing the PhoneInput component and useState hook from react in the aforementioned example. The value of the phone number is

then stored using the useState hook. After that, we use the installed package to add our phone input.

To run the app, enter the following command into the terminal.

npm start

output

Submit a Comment

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

Subscribe

Select Categories