41

I have a screen in my React Native application in which I have few text fields.

I was wondering if there is any way in which on screen load my keyword opens automatically and focuses on my first text input field?

I was searching for something like stateAlwaysVisible in android.

11 Answers 11

55

The keyboard should open automatically when <TextInput /> is focused. You can use the autoFocus prop to make it focus when the element mounts (link)

Sign up to request clarification or add additional context in comments.

9 Comments

autoFocus does not seem to fire when the page loads through stack navigation. It ends up focusing the textInput but does not open the keyboard.
Manual focus by refs doesn't trigger keyboard. There is a Keyboard.dismiss(), but I don't see a show() on React Native docs either.
@Dan same problem here. Trying to focus a TextInput by ref and open the Keyboard. Did you find any solution?
This answer does not answers the question, it is a workaround for a specific case. If one doesn't wants/can use autofocus, then this answer won't work. The Keyboard is not shown on focus
can confirm that autoFocus works on android with stack navigation
|
28

This trick worked for me

setTimeout(() => InputRef.current.focus(), 100)

2 Comments

Thanks for this. Works very well for me
I've added this timeout to the Modal "onShow" solution. Works fine now. thx. ( onShow={() => setTimeout(() => inputRef.current.focus(), 100)} )
16

My way (there was a problem with focusing and showing a keyboard on component render)

import { InteractionManager, TextInput } from 'react-native';

...

inputRef = React.createRef();

componentDidMount() {
  this.focusInputWithKeyboard()
}

focusInputWithKeyboard() {
  InteractionManager.runAfterInteractions(() => {
    this.inputRef.current.focus()
  });
}

render() {
  <TextInput ref={this.inputRef} />
}

Comments

14

another solution :)

import React, { useRef } from 'react'

export function mycomponent(props) {
   const inputRef = useRef();
   
   return(
         <TextInput 
           ref={inputRef}
           onLayout={()=> inputRef.current.focus()}>
         </TextInput>
   )
}

2 Comments

This is the best answer that just work ! In case you're trying to focus an input inside a modal, use the Modal onShow event instead of the TextInput onLayout and it will work flowlessly. <Modal visible={visible} onShow={() => inputRef.current?.focus()}/><TextInput ref={inputRef} /></Modal>
onLayout doesn't invoked when navigating back to that screen!
3

None of the solutions above worked for me when using a Modal. However, a combination of them did work.

Using the Modal's onShow and a setTimeout did the job for me.

<Modal
  onShow={() => {
    setTimeout(() => {
      inputRef?.current?.focus()
    }, 50)
  }}
>
  {/* ... */}
  <TextInput
    ref={inputRef}
  />
</Modal>

1 Comment

This is the only method that works for me. Thanks
1

It worked for me.

<TextInput
        autoFocus={false}
        autoCapitalize="none"
        onChangeText={(val) => {
            props.onChange(val);
        }}
        value={null}
        defaultValue={props.defaultValue}
        ref={(ref) => {

            if( ref !== undefined && ref && !ref.isFocused() ){

                ref.focus();
            }
        }}
        {...propsMerge}
    />

1 Comment

I guess you could remove the whole ref part and set autoFocus to true instead
0

This seems to be working in my simulator. Have not confirmed on a real device.

constructor(props) {
  super(props);
  this.buildNameTextInput = React.createRef();
}
<TouchableOpacity
  style={styles.mainButton}
  onPress={() => {
    this.buildNameTextInput = true
    this.props.setSaveBuildModal(true)
  }}
>
  <Text style={styles.mainButtonText}> Save Build </Text>
</TouchableOpacity>

<TextInput
  autoFocus={!!this.buildNameTextInput}
  ref={this.buildNameTextInput}
  placeholder="Type a Name"
  autoCapitalize="words"
  style={{...styles.heroBtnText, marginVertical: 50}}
  onChangeText={buildName => this.props.setCurrentBuildName(buildName)}
  value={this.props.buildName}
/>
  1. I needed the constructor to register the reference
  2. The handler sets a local variable to true
  3. autoFocus will trigger the field to be focused. The keyboard sometimes opens up on android simulator (this I cannot explain).
  4. ref is for the reference to the DOM element

Comments

0

You can maintain a ref to the TextInput as textInputRef and use this.textInputRef.focus()

Comments

0

This is how it looks in code, using the setTimeout() Hook

import { StyleSheet, Text, View, TextInput } from "react-native";
import React from "react";

const HomeScreen = () => {
  const inputRef = React.useRef();

  setTimeout(() => inputRef.current.focus(), 100);
  return (
    <View style={{ paddingVertical: 20 }}>
      <Text>circle</Text>
      <TextInput ref={inputRef} />
    </View>
  );
};

export default HomeScreen;

const styles = StyleSheet.create({});

2 Comments

wrap the setTimeOut with useEffect or it will be it will be created in every render!
Just for clarify some things: 1) setTimeout is not a hook, it's nothing but a JS function. 2) You need to wrap with useEffect hook, as said before. 3) It's a good practice to cancel it when component unmounts (returning a cleanup function in the end of useEffect), like following: useEffect(()=> { const timeout = setTimeout(() => inputRef.current.focus(), 100); return ()=> { clearTimeout(timeout) } }, [])
0

just use autoFocus prop of TextInput. It worked even in a modal :

<TextInput
    placeholder={placeholder || "Enter text"}
    value={text}
    onChangeText={setText}
    editable={!readOnly}
    autoFocus={true}
/>

Comments

-1

The selected solution did not work for me due to stack navigation (see comment of "SoundStage" on selected solution)

I added a new variable openTheKeyboard to the state initially set to false.

My hacky solution:

componentDidMount() {
  this.setState({ openTheKeyboard: true });
}

componentDidUpdate() {
  if (this.state.openTheKeyboard) {
    this.textInput.focus();
    this.setState({ openTheKeyboard: false });
  }
}

2 Comments

What could be the reasons if when calling .focus() the keyboard is not showing up ?
this.textInput.focus(); should instead be this.textInput.current.focus();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.