Tips for customizing a phone number input field in a React application

I have implemented a custom React phone number input field by referencing this link. However, I am unsure how to style it to match the appearance of my other input fields. You can view the current demo with my inputs here.

Below is the code snippet that I am working with. Any suggestions on how to improve the styling would be greatly appreciated:

            <PhoneInput
              name = "phoneNumber"
              type = "text"
              country={'us'}
              enableAreaCodes={true}
              onlyCountries={['us']}
              areaCodes={{us: ['999']}}
              inputProps={{
                name: 'phone',
                country:'us',
                required: true,
                autoFocus: true
              }}
              value={this.state.phone}
              onChange={this.handleOnChange}

           />

Code

import React, {useState} from 'react'
import {
  Form,
  Field
} from 'react-advanced-form'
import {
  Input,
  Button
} from 'react-advanced-form-addons'
// import 'react-phone-number-input/style.css'
// import PhoneInput from 'react-phone-number-input'
import PhoneInput from 'react-phone-input-2'
import 'react-phone-input-2/lib/style.css'


export default class RegistrationForm extends React.Component {
  registerUser = ({
    serialized,
    fields,
    form
  }) => {
    return fetch('https://backend.dev', {
      body: JSON.stringify(serialized)
    })
  }


  state = { phone: "" };

  handleOnChange = value => {
    console.log(value);
    this.setState({ phone: value }, () => {
      console.log(this.state.phone);
    });
  };

  handleAgreementCheckbox = () => {
      const currentTime = new Date();
      const eligibleUserDOB = new Date(currentTime.getFullYear() - 18, currentTime.getMonth(), currentTime.getDate());
      return currentTime>= eligibleUserDOB;
  };

  render() {
    return (
      <section className = "container">
        <Form action = {
          this.registerUser
        }
        onSubmitStart = {
          this.props.onSubmitStart
        }>
            <Input name = "firstName"
            label = "First name"
            required = {
              ({
                get
              }) => {
                return !!get(['lastName', 'value'])
              }
            }/>
            <Input name = "lastName"
            label = "Last name"
            required = {
              ({
                get
              }) => {
                return !!get(['firstName', 'value'])
              }
            }
            />

            <Input name = "emailAddress"
            type = "email"
            label = "Email Address"
            required />


            <PhoneInput
              name = "phoneNumber"
              type = "text"
              country={'us'}
              enableAreaCodes={true}
              onlyCountries={['us']}
              areaCodes={{us: ['999']}}
              inputProps={{
                name: 'phone',
                country:'us',
                required: true,
                autoFocus: true
              }}
              value={this.state.phone}
              onChange={this.handleOnChange}

            required/>


            <Input name = "dateOfBirth"
            type = "date"
            label = "Date of Birth"
            required />

            <Input name = "eligibleAge"
            type = "checkbox"
            label = "I agree"
            value = "unchecked"
            />
          <Button primary> Submit </Button>
        </Form>
      </section>
    );
  }
}

(Appreciate any guidance as I navigate the world of React!)

Answer №1

As outlined in the documentation, it is possible to provide class names and inline styles as props for each element. This can be achieved through:

<PhoneInput
  ...
  containerClass="my-container-class"
  inputClass="my-input-class"
  containerStyle={{
    border: "10px solid black"
  }}
  inputStyle={{
    background: "lightblue"
  }}
/>

For a demonstration, refer to this CodeSandbox example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Echo input and refresh on the current page upon submission

I am facing an issue with refreshing the page after submitting a form. I want to refresh the page so that the login attempt can be counted, but currently, the form is displayed without the page being refreshed to add to the count. This is my current code s ...

Using varying conventions for variable naming within a single program

I've encountered a minor problem that's been on my mind. I want to handle it in a more polished manner. When it comes to naming variables, I like to follow conventions. In NodeJs, I go with camelCasing. For databases like PostgreSQL, I stick to ...

Associate the callback function with a directive that does not have an isolated scope

Ensuring the correct context when binding a callback function to a directive is crucial. When working with an isolated scope, this task is easily accomplished. <bar-foo callback="mycontroller.callback()"></bar-foo> The directive code: ... ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

The controller does not initially receive the state when the handleSubmit function is first triggered, but it successfully receives it the second time

Utilizing cloudinary for user avatar image uploads within a next js application, I have implemented a backend controller file to handle the process of updating profile data in mongoDB with node js. The issue arises when trying to pass the URL of the cloudi ...

Define CSS styles based on the content of a specific cell within a table

Is there a way to target a <td> in CSS based on its content value? <table> <tr> <td>Name</td> <td>John</td> <tr> </table> For instance, how can I apply the color:bl ...

Loading animation vanishes prior to the second ajax request being made

Whenever an ajax call is initiated, I display a loading animation that stops once the ajax call is completed. This works perfectly when there's only one ajax call in a function. However, if there are two ajax calls within the same function, the loadin ...

Utilizing Lodash's uniqWith function, it allows us to specify how we want to

Currently, I am utilizing the lodash uniqWith method to eliminate duplicate items with the same id from my array. However, the lodash method retains the first duplicated item, whereas I actually want to keep the last duplicated item. Is there a way to ac ...

The concept of position() is often mistaken for a function

I am currently developing a slider and have included the code below: $(document).ready(function() { // MAKE SLIDER WIDTH EQUAL TO ALL SLIDES WIDTH var totalWidth = 0; $('.slide').each(function() { totalWidth = totalWi ...

Fixing the bootstrapValidator error in a PHP file: A step-by-step guide

Having trouble with bootstrapValidation() I created a PHP file and included all the Bootstrap 4.0 CDNs, then made a separate JavaScript file where I created a function called bootstrapValidator to check input length and emptiness using jQuery and Ajax. Ho ...

What is the best way to adjust the content of a Bootstrap Column to be at the bottom of the column

Currently diving into the world of Bootstrap for my personal website, I'm encountering a challenge in aligning the content of my sidebar to the bottom. My quest for a solution led me through numerous threads without success. <!-- wordsmith: < ...

What is the best way to position my "bar" div at the top of the page?

For the school presidentship voting system that I created, I am looking to enhance the user interface through website styling. In my administrator view, there are numerous codes displayed which require scrolling down frequently. Here is the code snippet ...

In order to showcase an image ahead of another (stay tuned),

Help! I'm facing a dilemma here. I have an abundance of adorable animal images with unique facial expressions, but there's one problem - the eyes are hidden! I desperately want to showcase those captivating eyes. This is what my code looks like. ...

Selecting an item from a dropdown menu using Selenium

Currently, I am tackling a test automation scenario that presents a challenge. Within a web form, there is a dropdown menu containing various items. My task is to select a specific item based solely on the expected content. I aim to choose 'PostgreS ...

Shifting the pagination outside of the slider in ReactJS and SwiperJS seems to be tricky. Despite trying to adjust the margins and padding, the pagination

I've been struggling with this issue for a while now. I need to move the pagination outside of the slider, but using padding or margin doesn't seem to work. It always remains inside the slider, and if I try to position it outside, it gets hidden. ...

404 error occurs when prefetching using Next.js <Link> tag

I recently created a Next.js application with dynamic routing, but I'm encountering some unusual behavior with the prefetching done by the <Link> component. Every now and then (usually after a rebuild, but not consistently), all the prefetch re ...

What is the definition of a type that has the potential to encompass any subtree within an object through recursive processes?

Consider the data structure below: const data = { animilia: { chordata: { mammalia: { carnivora: { canidae: { canis: 'lupus', vulpes: 'vulpe' } } } } }, ...

I am unable to view any graphics displayed using Three.js library

This particular piece of code focuses on Three.js and utilizes the main.js file: import * as THREE from 'three'; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); ...

Contrasts between Flash and HTML5

Now that YouTube has transitioned from flash to HTML5, what are the unique features and functionalities of HTML5 that set it apart from flash? I am also curious to learn a more in-depth and intriguing aspect of HTML5 beyond what can be found through a sta ...

Ways to remove unnecessary div containers in Nuxt js?

This is an example of my page: https://i.sstatic.net/CYCRL.png Showing the Nuxt layout: <template> <div> <Nuxt /> </div> </template> After being compiled by Nuxt, it generates: https://i.sstatic.net/CYdX3.png You ...