Ryan Pergent
Ryan Pergent

Reputation: 5366

Persist keyboard when showing a React Native modal

I want to show a modal when the user taps a button, without dismissing the keyboard. Unfortunately, the keyboard is dismissed as soon as the modal appears.

Minimum repro case:

import * as React from "react";
import { Button, Modal, Text, TextInput, View } from "react-native";

function TestComp() {
    const [showingModal, setshowingModal] = React.useState(false);
    return (
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center", marginTop: 22 }}>

            <Modal visible={showingModal} transparent onRequestClose={() => setshowingModal(false)}>
                <View style={{ flex: 1, marginTop: 22 }}>
                    <Button title={"hide modal"} onPress={() => setshowingModal(false)} />
                </View>
            </Modal>

            <TextInput placeholder="Focus to show keyboard" />
            <Button title={"Show modal"} onPress={() => setshowingModal(true)} />
        </View>
    );
}

FYI, I am using expo.

How can I force the keyboard to persist?

Upvotes: 9

Views: 4898

Answers (1)

alain00
alain00

Reputation: 171

You can add a hidden TextInput inside the modal with the attribute autoFocus, it's a pretty simple workaround, when you press the button and the modal showsup the focus will go to the hidden input keeping the keyboard open

https://snack.expo.io/Q01r_WD2A

import * as React from 'react';
import {Button,Modal,Text,TextInput,View,Keyboard,ScrollView} from 'react-native';

export default function TestComp() {
  const [showingModal, setshowingModal] = React.useState(false);

  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center", marginTop: 22 }}>
      <Modal
        visible={showingModal}
        transparent
        onRequestClose={() => setshowingModal(false)}>
        <View style={{ flex: 1, marginTop: 22 }}>
          <TextInput autoFocus={true} placeholder="Autofocus to keep the keyboard" style={{display: 'none'}} />
          <Button title={'hide modal'} onPress={() => setshowingModal(false)} />
        </View>
      </Modal>

      <TextInput placeholder="Focus to show keyboard" />
      <Button title={'Show modal'} onPress={() => setshowingModal(true)} />
    </View>
  );
}

Upvotes: 4

Related Questions