Search code examples
javascriptreactjsyupreact-phone-number-input

Is there any way to pass props to textfield in react phone number input library?


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.


Solution

  • 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.