Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus input on load of Modal in React Native

Tags:

react-native

I'm using React Native's Modal component. I would like to focus on a TextInput & show keyboard when the Modal is visible.

Any ideas how to do this?

like image 846
Molly Harper Avatar asked Mar 11 '17 01:03

Molly Harper


Video Answer


2 Answers

You can add a reference to the text input and call the focus method from the onShow handler of the Modal.

    import React, { Component } from 'react';
    import { Modal, Text, TextInput, TouchableHighlight, View } from 'react-native';
    
    export default class ModalExample extends Component {
    
      state = {
        modalVisible: false,
      }
    
      render() {
        return (
          <View style={{flex: 1, justifyContent:'center', alignSelf: 'center'}}>
            <Modal
              animationType={"slide"}
              transparent={false}
              visible={this.state.modalVisible}
              onShow={() => { this.textInput.focus(); }}
              >
             <View style={{backgroundColor: 'green', marginTop: 50, width: 300, padding: 50, alignSelf: 'center'}}>
              <View>
                <Text>Hello World!</Text>
                <TextInput
                  ref={(input) => { this.textInput = input; }}
                  style={{ padding: 20, backgroundColor: 'white', color: 'red' }}
                />
              </View>
             </View>
            </Modal>
    
            <TouchableHighlight onPress={() => {
              this.setState({modalVisible: true});
            }}>
              <Text>Show Modal</Text>
            </TouchableHighlight>
    
          </View>
        );
      }
    }
like image 185
Saleel Avatar answered Oct 10 '22 00:10

Saleel


Set the property autoFocus on the TextInput to true:

<TextInput
  autoFocus={true}
/>
like image 1
Maximilian Dietel Avatar answered Oct 10 '22 02:10

Maximilian Dietel