How to use material-ui TextField with react-phone-number-input

Viewed 26137

I'd like to supply a material UI TextField component to the PhoneInput component from react-phone-number-input as the inputComponent prop.

However, I don't seem to be able to successfully apply the ref. Although I see the Material UI TextField component rendered to the UI and state is successfully updated with the value, it keeps loosing focus after the first value has been typed.

import React, { forwardRef, createRef } from 'react';
import { TextField } from '@material-ui/core';
import 'react-phone-number-input/style.css';
import PhoneInput from 'react-phone-number-input';

const SampleComponent = ({ handleChange }) => {

const phoneInput = forwardRef((props, ref) => {

return (
  <TextField
    inputRef={ref}
    fullWidth
    label="Phone Number"
    variant="outlined"
    name="phone"
    onChange={handleChange}
  />
  );
});

const ref = createRef();
return (
    <PhoneInput ref={ref} inputComponent={phoneInput} />
   );
  };
2 Answers

So I was able to get it to work using the following method. Any suggestions on how to improve this are more than welcome.

I have a separate file called PhoneNumber.jsx

import { forwardRef } from 'react'
import TextField from '@material-ui/core/TextField'
import { makeStyles } from '@material-ui/core/styles'

const useStyles = makeStyles(theme => ({
  input: {
    backgroundColor: '#fff'
  }
}))

const phoneInput = (props, ref) => {
  const classes = useStyles()

  return (

    <TextField
      {...props}
      InputProps={{
        className: classes.input
      }}
      inputRef={ref}
      fullWidth
      size='small'
      label='Phone Number'
      variant='outlined'
      name='phone'
    />
  )
}
export default forwardRef(phoneInput)

And my form file:

import PhoneInput from 'react-phone-number-input'
import CustomPhoneNumber from '../components/prebuilt/PhoneNumber'
...
<PhoneInput
   placeholder='Enter phone number'
   value={phone}
   onChange={setPhone}
   inputComponent={CustomPhoneNumber}
/>
...

There is also a package for Material UI v5 (or MUI) called Mui tel input and it's working with React 17 and 18 !

Simply way to use. Phone validation available too.

Check the doc here : https://github.com/viclafouch/mui-tel-input

import React from 'react'
import { MuiTelInput } from 'mui-tel-input'

const MyComponent = () => {
  const [value, setValue] = React.useState('')

  const handleChange = (newValue) => {
    setValue(newValue)
  }

  return <MuiTelInput label="Phone" fullWidth value={value} onChange={handleChange} />
}

Related