Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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} />
   );
  };
like image 368
insivika Avatar asked Mar 29 '20 03:03

insivika


Video Answer


1 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}
/>
...
like image 129
grigs Avatar answered Nov 14 '22 23:11

grigs