How to add mobile number input with country code in React

Creating custom component is always fun. But it definitely takes time to create one. Sometimes we don’t have much time to spend on creating solution from scratch. In that case we can use pre exists components. In this article we will gonna learn how to add a mobile number input with country code in React.

What is react-phone-input-2 ?

This is a very good package for mobile number input with country code functionality. This is very customizable and at the same time super easy to use.

It comes with a lot of features like adding preferred country. Showing only some regions or showing only some countries etc.

Installation and Usage

Like any other package you can install it from npm using below command.

npm install react-phone-input-2 --save

After the installation you need to import the PhoneInput and its styling to you file.

import PhoneInput from 'react-phone-input-2'
import 'react-phone-input-2/lib/style.css'

Put below code in your component.

<PhoneInput
  country={'us'}
  value={this.state.phone}
  onChange={phone => this.setState({ phone })}
/>

This code will gonna show

or if you are using functional components you can use something like this.

  const [phone, updatePhone] = useState("");

 <PhoneInput country={"us"} value={phone} onChange={updatePhone} />

Input props

To pass props to input element you can use inputProps prop.

<PhoneInput
  inputProps={{
    name: 'phone',
    required: true,
    autoFocus: true
  }}
/>

Regions

You can also pass regions to be shown in the input as well.

<PhoneInput
  country='us'
  regions={['north-america', 'carribean']}
/>

Checkout full docs here.

Reusable hook for handling Inputs in React

Categories: Reactjs

1 Comment

How to make custom tooltip component in React - Blog React · November 5, 2020 at 3:52 am

[…] How to add mobile number input with country code in React […]

Comments are closed.