catamphetamine / react-phone-number-input

React component for international phone number input
http://catamphetamine.gitlab.io/react-phone-number-input/
MIT License
925 stars 194 forks source link

Unable to link Phone Input and Material-UI TextField #354

Closed waynegrigsby closed 4 years ago

waynegrigsby commented 4 years ago

I'm attempting to render a Phone Input field while using Material-UI styling but cant get the formatting right. I have a codesandbox up and running as a demo. If someone could take a look, I'd really appreciate it. The styling in the sandbox is not how it actually renders in my app, but the errors are the same. Everything seems fine until I enter text. I can only enter text after selecting the input, for every entry...

  let customPhoneInput = (props, ref) => (
    <TextField
      inputRef={ref}
      fullWidth
      focus
      size="small"
      variant="outlined"
    />
  );

  customPhoneInput = forwardRef(customPhoneInput);
         <PhoneInput
            placeholder="Enter phone number"
            inputComponent={customPhoneInput}
            name="Phone"
            value={phone}
            onChange={setPhone}
         />
waynegrigsby commented 4 years ago

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 React, { 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}
/>
...
ballad89 commented 4 years ago

@waynegrigsby I can't spot what you did differently in both code snippets ... what was the gotcha ?

catamphetamine commented 4 years ago

@ballad89 The reason the component "wasn't working" was because @waynegrigsby created the custom input component on every render instead of importing it from another file.