<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adarsh Dalvi on Medium]]></title>
        <description><![CDATA[Stories by Adarsh Dalvi on Medium]]></description>
        <link>https://medium.com/@adarshdalvi197?source=rss-2145689a323d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iFxcjmDRVt82W7_vo6oqeA.jpeg</url>
            <title>Stories by Adarsh Dalvi on Medium</title>
            <link>https://medium.com/@adarshdalvi197?source=rss-2145689a323d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:57:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adarshdalvi197/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating a Reusable Phone Input Component with React, Next.js , and TypeScript]]></title>
            <link>https://blog.stackademic.com/creating-a-reusable-phone-input-component-with-react-next-js-and-typescript-9bd14ddacc28?source=rss-2145689a323d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bd14ddacc28</guid>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-phone-input-2]]></category>
            <category><![CDATA[phone-number-validation]]></category>
            <dc:creator><![CDATA[Adarsh Dalvi]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 11:38:25 GMT</pubDate>
            <atom:updated>2024-01-16T01:54:59.683Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a Reusable Phone Input Component with React, Next.js , and TypeScript</h3><blockquote>Dealing with diverse phone number formats can be puzzling. In this article, we’ll create a reusable phone input using <strong>React Phone Input 2</strong> and <strong>React Form Hook</strong> for seamless control. <strong>Google’s libphonenumber</strong> will handle robust validation based on country codes, while <strong>TypeScript</strong> ensures error-free, type-safe code. <strong>Tailwind</strong> streamlines styling, resulting in a versatile phone input for <strong>React</strong> and <strong>Next.js</strong> 14 projects. The end result? A seamless and adaptable solution for handling phone numbers, making form handling a breeze.</blockquote><h4>Getting Started: Installing Required Libraries</h4><p>Before we delve into the creation of our reusable phone input component, let’s ensure your Next.js project is equipped with the essential tools. Assuming you’ve already set up a basic Next.js project with TypeScript and Tailwind CSS, we’ll now add the additional libraries required for our phone input component.</p><p>Here are the key tools we’ll be integrating:</p><ol><li><strong>React Phone Input 2</strong>: A library for creating a user-friendly phone input interface.</li></ol><pre>npm install react-phone-input-2</pre><p><strong>2. React Hook Form</strong>: Essential for seamless control of our form and input elements.</p><pre>npm install react-hook-form</pre><p><strong>3. Google’s libphonenumber</strong>: Google’s common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers.</p><pre>npm install google-libphonenumber --save<br>npm install --save-dev @types/google-libphonenumber  //for typescript support</pre><p><strong>4. Tailwind CSS’s Form Plugin: </strong>A plugin that provides a basic reset for form styles that makes form elements easy to override with utilities.</p><pre>npm install -D @tailwindcss/forms</pre><p>Then add the plugin to your tailwind.config.ts file:</p><pre>const config: Config = {<br>    content: [<br>        //....<br>    ],<br>    theme: {<br>        //...<br>    },<br>    plugins: [<br>        require(&#39;@tailwindcss/forms&#39;)({<br>            strategy: &#39;class&#39;,<br>        }),<br>    ],<br>};</pre><h4>Configuring Our Custom Phone Input Component</h4><p>With the essential libraries in place, it’s time to configure our custom phone input component to ensure a seamless integration. Follow these steps for a smooth setup:</p><p><strong>Importing necessary modules, components and defining Prop-Types for:<br>PhoneNumberInput.tsx</strong></p><pre>//PhoneNumberInput.tsx<br><br>import {<br>    Control,<br>    FieldValues,<br>    Controller,<br>    FieldErrors,<br>    UseFormSetValue,<br>} from &#39;react-hook-form&#39;;<br>import PhoneInput, { CountryData } from &#39;react-phone-input-2&#39;;<br>import &#39;react-phone-input-2/lib/style.css&#39;;<br>import libphonenumber from &#39;google-libphonenumber&#39;;<br>import { useState } from &#39;react&#39;;<br><br>// Define props for the PhoneInput component<br>interface PhoneInputProps {<br>    id: string; // Input identifier for referencing and rendering<br>    control: Control&lt;FieldValues, any&gt;; // React Hook Form&#39;s &#39;control&#39; prop for form communication<br>    errors: FieldErrors;  // React Hook Form&#39;s &#39;errors&#39; prop for validation messages<br>    setValue: UseFormSetValue&lt;FieldValues&gt;;  // React Hook Form&#39;s &#39;setValue&#39; prop for dynamic input value setting<br>    isSubmitted: boolean; // Flag indicating form submission status<br>}</pre><p>As we integrate our custom phone input, we face a challenge: React Phone Input 2’s onChange clashes with React Hook Form&#39;s register method. To address this, we&#39;re choosing React Hook Form&#39;s Controller component.</p><p>Here’s the breakdown:</p><p><strong>Conflict Warning</strong>: React Phone Input 2 relies on its own onChange, causing a clash with React Hook Form&#39;s register.</p><p><strong>Using the Controller</strong>: To resolve this, we’re turning to React Hook Form’s Controller component for a seamless fix.</p><p><strong>Easy Input Management</strong>: The isSubmitted, errors, and setValue functionalities come from the useForm hook. Importantly, these values are accessed through our form component, asserting its control over the input and ensuring it operates within defined parameters.</p><p><strong>With these aspects clarified, let’s dive into building our component. Now, we’ll proceed to define all the necessary state and functions for this component.</strong></p><p>The phoneNumberData state is crucial for managing the selected country’s code and dial code in the phone input. The <strong><em>CountryData</em></strong> interface used here is sourced from the <strong>React Phone Input 2</strong> library.</p><pre>//PhoneNumberInput.tsx<br><br>// State to manage phone number data(to manage country code and dial code)<br>const [phoneNumberData, setPhoneNumberData] = useState&lt;CountryData&gt;({<br>    name: &#39;INDIA&#39;,  <br>    dialCode: &#39;+91&#39;,  <br>    countryCode: &#39;in&#39;, <br>    format: &#39;+.. .....-.....&#39;,<br> });<br><br>/*<br>    Optionally, you can pre-fill the country code and other information <br>    of your choice as default values. Ensure that these values are in <br>    the correct format and adhere to the appropriate spelling conventions.<br><br>    For Example: {<br>      name:&#39;United States&#39;,<br>      dialCode:&#39;+1&#39;,<br>      countryCode: &#39;us&#39;,<br>      format: &#39;+. (...) ...-....&#39;<br>    }<br>*/</pre><p><strong>Validating Phone Numbers</strong>: The validatePhoneNumber function ensures that the entered phone number adheres to the expected format based on the provided country information. For the purpose of this tutorial, the validation focuses on checking whether the length of the actual phone number (excluding the country code) matches the example number length specific to the selected country. This straightforward validation approach offers a starting point. You can customize the logic according to your specific requirements.</p><pre>// PhoneNumberInput.tsx<br><br>// Validates the phone number format based on country information<br>const validatePhoneNumber = (<br>    value: string, // The phone number input value (includes the country code)<br>    inputInformation: CountryData // Country information for validation(dialcode and country code)<br>) =&gt; {<br>    let isValid = true; // Assume the number is initially valid<br>    const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();  // Get an instance of libphonenumber<br>    <br>    // Extract the actual phone number (excluding the country code)<br>    const phoneNumber = value.substring(inputInformation.dialCode.length);<br>    <br>    // Get the length of an example number based on the country code for validation<br>    const exampleNumberLengthByCountryCode = phoneUtil <br>        .getExampleNumber(inputInformation.countryCode) <br>        .getNationalNumber()<br>        ?.toString().length;<br><br>    // Check if the input length matches the example number length<br>    if (phoneNumber.length !== exampleNumberLengthByCountryCode){<br>      return false;<br>    }<br>    <br>    // Return the validation result<br>    return isValid;<br>};</pre><p>The function, handleOnChange, manages changes in the phone input. It sets the input value using setValue from React Hook Form, activating validation only if the form has been submitted.</p><pre>// PhoneNumberInput.tsx<br><br>// Function to handle onChange event of the phone input<br>const handleOnChange = (value: string, inputData: CountryData) =&gt; {<br>    setValue(id, value, { shouldValidate: isSubmitted });<br>    setPhoneNumberData(prevData=&gt;inputData);<br>};</pre><p><strong>With the essential states and functions in place, next step is to seamlessly integrate them into our JSX code.</strong></p><pre>// PhoneNumberInput.tsx<br><br>const PhoneNumberInput: React.FC&lt;PhoneInputProps&gt; = ({<br>    control,<br>    id,<br>    errors,<br>    setValue,<br>    isSubmitted,<br>}) =&gt; {<br>    <br>    // States and functions<br><br>    return (<br>        // Use Controller component from react-hook-form<br>        &lt;Controller<br>            name={id}<br>            control={control}<br>            // Define rules for validation<br>            rules={{   <br>                required: &#39;Phone number is required!&#39;,<br>                validate: (fieldValue) =&gt; {  <br>                    const isValid = validatePhoneNumber(<br>                        fieldValue,<br>                        phoneNumberData<br>                    );<br>                    return isValid || &#39;Phone Number is not valid!&#39;;<br>                },  <br>            }}<br><br>            render={({ field }) =&gt; {<br>                return (<br>                    &lt;div className=&quot;flex flex-col mb-6&quot;&gt;<br>                        {/* PhoneInput component */}<br>                        &lt;PhoneInput<br>                            onChange={(value, inputData) =&gt;<br>                                handleOnChange(value, inputData as CountryData)<br>                            }<br>                            value={field.value}<br>                            country={&#39;in&#39;}<br>                            inputStyle={{ width: &#39;100%&#39; }}<br>                            inputProps={{<br>                                className: `<br>                                    form-input<br>                                    py-3<br>                                    pr-4<br>                                    pl-[45px]<br>                                    border-solid<br>                                    border<br>                                    rounded-md<br>                                    text-gray-900<br>                                    shadow-sm ring-1<br>                                    ring-inset<br>                                    sm:text-[1.4rem]<br>                                    focus:ring-1<br>                                    focus:ring-inset<br>                                    focus:ring-emerald-600<br>                                    ${errors[id] &amp;&amp; &#39;focus:ring-red-500&#39;}<br>                                `,<br>                            }}<br>                            placeholder=&quot;Enter your phone number&quot;<br>                            enableSearch<br>                            countryCodeEditable={false}<br>                            autoFormat<br>                        /&gt;<br>                        {/* Display error message if any */}<br>                        {errors[id] &amp;&amp; errors[id]?.message &amp;&amp; (<br>                            &lt;span className=&quot;text-red-500 text-lg mt-1.5&quot;&gt;<br>                                {errors[id]?.message as React.ReactNode}<br>                            &lt;/span&gt;<br>                        )}<br>                    &lt;/div&gt;<br>                );<br>            }}<br>        /&gt;<br>    );<br><br>}<br><br>export default PhoneNumberInput;</pre><p>Now that our custom phone input component is ready, let’s integrate it into our form. Incorporating &lt;PhoneNumberInput /&gt; is a breeze, and with the essential props like id, control, errors, setValue, and isSubmitted already defined, this integration step requires no elaborate explanations. Let&#39;s proceed with this final step.</p><p><strong>Form.tsx</strong></p><pre>&#39;use client&#39;         <br><br>/** &quot;use client&quot; is used to declare a boundary between a Server and <br>   Client Component modules. This means that by defining a <br>   &quot;use client&quot; in a file, all other modules imported into it, <br>   including child components, are considered part of the client bundle. **/<br><br>import PhoneNumberInput from &#39;@/app/components/inputs/PhoneInput&#39;;<br>import { FieldValues, SubmitHandler, useForm } from &#39;react-hook-form&#39;;<br><br>function Form(){<br>  const {<br>        setValue,<br>        control,<br>        handleSubmit,<br>        formState: { errors, isSubmitted },<br>   } = useForm&lt;FieldValues&gt;();<br><br>   const submitForm: SubmitHandler&lt;FieldValues&gt; = (data) =&gt; {<br>     // Your for submit logic goes here<br>   }<br><br>   return (<br>      &lt;form<br>          onSubmit={handleSubmit(submitForm)}<br>          className=&quot;flex flex-col &quot;<br>        &gt;<br>            {/* Your Other Input components*/}<br><br>            &lt;PhoneNumberInput<br>                control={control}<br>                setValue={setValue}<br>                id=&quot;phoneNumber&quot;<br>                errors={errors}<br>                isSubmitted={isSubmitted}<br>            /&gt;<br><br>            &lt;button type=&#39;submit&#39;&gt;submit&lt;/button&gt;<br>       &lt;/form&gt;<br>   );<br>}<br><br>export default Form;<br></pre><p><strong>Alright, with all the steps completed, let’s see the result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*alZTTydA7yFMJzVq-nXvcQ.png" /><figcaption>No interactions made yet</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*dXKeZiaJpM9ASJXF7pTVKw.png" /><figcaption>changing the country code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*r9LaZDE7fRHATNacON60Hg.png" /><figcaption>submitting empty form</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*CGxXOjRZnlD4L6JT0XZk0w.png" /><figcaption>submitting an invalid input</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*EBpYNT-_f-R199SfItek2Q.png" /><figcaption>Submitting a valid input</figcaption></figure><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq">X</a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> |</strong> <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bd14ddacc28" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/creating-a-reusable-phone-input-component-with-react-next-js-and-typescript-9bd14ddacc28">Creating a Reusable Phone Input Component with React, Next.js , and TypeScript</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>