Let's consider the following situation:
There is a page with an Input
and a Button
to open a modal.
In the modal, there is the other Button
to close this modal, to focus the Input
and to show the Keyboard
.
The problem:
Right after pressing the other Button
to close the modal, to focus the Input
and to show the Keyboard
the following happens:
Input
has focus.Keyboard
is NOT shown.This is my code:
import React, { useState, useEffect, useRef } from 'react';
import { View } from 'react-native';
import { Button, Input, Overlay } from 'react-native-elements';
const App = () => {
const [isInputFocused, setInputFocused] = useState(false);
const [isModalVisible, setModalVisible] = useState(false);
const inputRef = useRef(null);
useEffect(() => {
isInputFocused ? inputRef.current.focus() : inputRef.current.blur();
}, [isInputFocused]);
const handleInputFocus = () => setInputFocused(true);
const handleInputBlur = () => setInputFocused(false);
const handleOpenModalButtonPress = () => setModalVisible(true);
const handleFocusInputButtonPress = () => {
setModalVisible(false);
setInputFocused(true);
};
const handleModalBackdropPress = () => setModalVisible(false);
return (
<View style={{ justifyContent: 'space-around', flex: 1, padding: 25 }}>
<Input
ref={inputRef}
onFocus={handleInputFocus}
onBlur={handleInputBlur}
/>
<Button
title="Open Modal"
onPress={handleOpenModalButtonPress}>
</Button>
<Overlay visible={isModalVisible} onBackdropPress={handleModalBackdropPress}>
<Button title="Focus Input and Open Keyboard" onPress={handleFocusInputButtonPress} />
</Overlay>
</View>
);
};
export default App;
You can see it live here.
The question:
Is it possible to open the keyboard programmatically? It would probably solve my problem.
If not, could somebody explain what I am missing with my current approach or suggest a different solution?
Thanks in advance.
P.S.
react-native-elements
package is used here only for styling purposes.
Input
inherits all TextInput
props, Overlay
- Modal
props, and Button
- TouchableWithoutFeedback
props.
So, I suppose, they should behave almost the same as casual React Native TextInput
, Modal
and TouchableWithoutFeedback
.
Currently, I have tested this code only on Android.
It appears there are two issues:
setTimeout(() => setInputFocused(true), 500);
const handleOpenModalButtonPress = () => {
setModalVisible(true);
setInputFocused(false);
};
Perhaps there is a more general solution.