CaioQuirinoMedeiros / react-native-currency-input

A simple currency input component for both iOS and Android
https://www.npmjs.com/package/react-native-currency-input
MIT License
158 stars 25 forks source link

FakeCurrencyInput: ref is always undefined #10

Closed seyaobey-dev closed 3 years ago

seyaobey-dev commented 3 years ago

I'm using FakeCurrencyInput and I would like to immediately focus the currency input when the user lands on the screen where it is using. In this way, a keyboard and a cursor will appear.

To do that, I create a ref so I can call ref.current.focus() on useEffect. But ref.current is always undefined. But if I do a hot reloading (I'm using react-native + expo), then the ref has a valid value. Here is my code simplified:

...
 const ref = useRef(null);

 useEffect(() => {
    ref.current.focus(); // <-- undefined 
}, []);

return (
   <FakeCurrencyInput
       ref={ref} // <-- !!
       value={value)
       ...
   />
)

Is this a known bug?

Thanks for this library and the support

CaioQuirinoMedeiros commented 3 years ago

Hi @seyaobey-dev . I couldn't reproduce this bug... Trying to focus the input that way was always problematic on ReactNative, but I've never seen it crashing by being undefined 🤔

Anyway, I have two suggestions for you:

  1. Use the autoFocus property from TextInput
    
    // useEffect(() => {
    //   ref.current.focus();
    // }, [])

return ( <FakeCurrencyInput // ref={ref} autoFocus // <-- value={value) ... /> )


2. Wrap your focus call on a `setTimeout`:
```javascript
useEffect(() => {
  setTimeout(() => {
    ref.current?.focus();
  }, 100); // <-- try different values
}, [])
seyaobey-dev commented 3 years ago

Thank you so much for your quick answer. autofocus has done the trick!