0
votes

This code is not working, been trying multiple version, can someone please help? It generates an error of going from controlled to uncontorlle, plus the mask doesn't work at all, what am I missing?

https://github.com/react-hook-form/react-hook-form/issues/1255

Here is a codesandbox: https://codesandbox.io/s/sad-shamir-nnh0c?fontsize=14&hidenavigation=1&theme=dark

import React, { useState } from 'react'
import { TextField } from '@material-ui/core'
import InputMask from 'react-input-mask'
import { useFormContext, Controller} from 'react-hook-form'

const PhoneInputMask = (props) => {
  const { inputRef, ...other } = props;
  return (
    <InputMask
      {...other}
      mask={['(' , '+', /[3]/, /[5-8]/, /[1-9]/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/]}
      inputRef={inputRef}
      alwaysShowMask={true}
    />
  )
}


const PhoneInput = (props) => {
  const [textMask, setTextMask] = useState()
  const handleChange = (event) => setTextMask(event.target.value)
  const { errors, register, control } = useFormContext()

  const { name, label, registerContext } = props
  return (
    <Controller
      name={name}
      control={control}
      defaultValue=""
      render={props => (
      <TextField
        margin="normal"
        InputProps={{
          inputComponent: PhoneInputMask,
          value:textMask,
          onChange: handleChange,
        }}
        name={name}
        id={name}
        inputRef={register(registerContext)}
        label={label}
        error={!!errors[name]}
        helperText={(errors[name]) ? errors[name].message : null}
      />)}
    />
  )
}

export default PhoneInput
1

1 Answers

1
votes
<Controller
    name="phone"
    control={control}
    defaultValue=""
    render={({ field: { onChange, value } }) => (
        <InputMask mask="+999999999999" value={value} onChange={onChange}>
            {
                inputProps => (
                    <TextField
                        error={!!errors.phone?.message}
                        label="Phone"
                        variant="outlined"
                        type="text"
                        fullWidth
                        required
                        {...inputProps}
                    />
                )
            }
        </InputMask>
    )}
/>

For error of going from controlled to uncontorlled value, you need to add defaultValue=""