0

react-native: 0.65.1

I'm trying to open keyboard when Modal is opened (by autofocusing TextInput inside it)

  • Firstly I tried with autoFocus prop and it absolutely works on ios, and Android in DEV mod (Android in Prod mod fully ignore this prop)

  • To fix android I tried solution with ref.focus() inside componentDidUpdate (useEffect in my case) from this post, but it is ignored too

Then I tried to run .focus() inside setInterval (in code example), and it started to work (but not each time when I open a Modal).

Also my TextInput is inside Modal:

import {Modal} from 'react-native';

Question: Is it a bug with TextInput component? And Is there any more stable solutions with autoFocus, or maybe another way to open keyboard with screen opening?

import {TextInput} from "react-native";

export const Input: React.FC = () => {
  const inputRef = useRef<TextInput>(null);

  useEffect(() => {
    if (!isFocused.current && inputRef.current) {
      setTimeout(() => {
        inputRef.current?.focus();
      }, 0);
    }
  });

  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => {
        isFocused.current = true;
      }
    );
    return () => {
      keyboardDidShowListener.remove();
    };
  }, []);

  return (
    <TextInput value={'MOCK VALUE!'} ref={inputRef} autoFocus/> // autoFocus useLess for android here
  )
}```

Dmitry
  • 1
  • 1

1 Answers1

0

You forgot to add dependency array in the first useEffect.

import {TextInput} from "react-native";

export const Input: React.FC = () => {
  const inputRef = useRef<TextInput>(null);

  useEffect(() => {
    if (!isFocused.current && inputRef.current) {
      setTimeout(() => {
        inputRef.current?.focus();
      }, 0);
    }
  },[]); // add dependency array here

  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => {
        isFocused.current = true;
      }
    );
    return () => {
      keyboardDidShowListener.remove();
    };
  }, []);

  return (
    <TextInput value={'MOCK VALUE!'} ref={inputRef} autoFocus/> // autoFocus useLess for android here
  )
}
abdemirza
  • 629
  • 4
  • 16