thegamenicorus / react-native-phone-input

Phone input box for React Native
https://www.npmjs.com/package/react-native-phone-input
MIT License
394 stars 447 forks source link

Invariant Violation: Invariant Violation: Function components cannot have refs. Did you mean to use React.forwardRef()? #130

Closed Mnabawy closed 4 years ago

Mnabawy commented 4 years ago

here is my child component ` render() { return (

{ this.phone = ref; }} onPressFlag={this.onPressFlag} />
);

} }` here is my parent component

<PhoneInput style={styles.phoneInput} ref="phone" onChangeText={handleChange("phoneInput")} onBlur={handleBlur("phoneInput")} placeholder="enter phone number" autoFocus offset={15} />

jaydenwindle commented 4 years ago

Hey @Mnabawy! Can you please attach a full code sample? It's a little hard to tell what the issue is here from the info you provided.

My initial guess is that your parent component is a functional component, so using the deprecated ref="phone" would cause this error. Have you tried using a callback ref on PhoneInput in your parent component?

Mnabawy commented 4 years ago

actually my question is how to use your package as a reusable component ? with function component and hooks

jaydenwindle commented 4 years ago

Sure! Here's an example of using this package with a functional component and hooks:

import React, { useRef, useState } from 'react';
import { Text, View } from 'react-native';

import PhoneInput from 'react-native-phone-input';

export default function App() {
  const [isValidNumber, setIsValidNumber] = useState(false)
  const phoneRef = useRef(undefined);

  return (
    <View>
      <PhoneInput
        ref={phoneRef}
        onChangePhoneNumber={value => {
          setIsValidNumber(phoneRef.current.isValidNumber())
        }} 
      />
      <Text>Is Valid Number: {isValidNumber ? 'Yes' : 'No'}</Text>
    </View>
  );
}

You can see a working example here: https://snack.expo.io/@jaydenwindle/react-native-phone-input-ref-example

Mnabawy commented 4 years ago

what about using a custom example

jaydenwindle commented 4 years ago

@Mnabawy what do you mean by a custom example? Do you mean adding the hooks example to the readme? If so, feel free to submit a PR :)