Home > Software engineering >  Is there any way to pass props to textfield in react phone number input library?
Is there any way to pass props to textfield in react phone number input library?

Time:08-25

I am using react-phone-number-input library to take phone number inputs from users with country code. I added extra text-field as an inputComponent props of this component. My component is,

<PhoneInput
   international
   defaultCountry="BD"
   placeholder="Enter phone number"
   value={phoneNumber}
   onChange={handlePhoneNumberOnChange}
   countryCallingCodeEditable={false}
   inputComponent={TextFieldPhoneInput}
/>

Is there any way to pass some others props to the TextFieldPhoneInput component which i used inside inputComponent? Reasons behind passing props to the TextFieldPhoneInput is, i want to validate the textfield and show some error messages as label after validation.

CodePudding user response:

You can do it like this

<PhoneInput
  placeholder="Enter phone number"
  value={value}
  onChange={setValue}
  inputComponent={forwardRef((props, ref) => <input ref={ref} {...props} id=my_input_id_extra_passing_it" />)}
/>

Assuming you know how and where to import forwardRef

CodePudding user response:

I solved this after adding my needed props touched, errors, directly to the component and wrapped the inputComponent with forwardRef. My Solution is,

<PhoneInput
  international
  defaultCountry="BD"
  placeholder="Enter phone number"
  value={phoneNumber}
  onChange={handlePhoneNumberOnChange}
  countryCallingCodeEditable={false}
  touched={touched}
  errors={errors}
  inputComponent={TextFieldPhoneInput}
  />

and inside TextFieldPhoneInput component,

const TextFieldPhoneInput = (props, ref) => {
    const {touched,errors} = props
    const classes = useStyles()
    return (
        <TextField
            {...props}
            InputProps={{
                className: classes.input
            }}
            inputRef={ref}
            fullWidth
            // size='small'
            label='Phone Number'
            variant='outlined'
            name='phone'
            error={Boolean(touched && errors)}
            helperText={touched && errors}
        />
    );
};

TextFieldPhoneInput.propTypes = {};
export default forwardRef(TextFieldPhoneInput)

Now, everything works fine.

  • Related