Open In App

How to add Phone Input in Next.js ?

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to learn how we can add phone input in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac.

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.

Steps to Create Next.js App and Install Required Modules

You can create a new NextJs project using the below command:

npx create-next-app gfg

Move to the project directory

cd 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:

The updated dependencies in the package.json file are:

"dependencies": {
"next": "14.2.4",
"react": "^18",
"react-dom": "^18",
"react-phone-input-2": "^2.15.1"
}

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.

JavaScript
// Filename - index.js

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>NextJs Phone Input - GeeksforGeeks</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 run dev

Output:


Next Article

Similar Reads