Search code examples
javascriptandroidreact-nativetextinput

Focus a specific element given its key


I'm developing a small app to guess a word. Instead of a single TextInput I want to give clues about how many characters the word have and maybe even start with some characters already revealed.

To do that I'm creating one TextInput for each character, then I'm setting the first TextInput with autofocus=true.

What I need is that when the user inputs a character in the current TextInput the focus jumps to the next one.

To create the Inputs, I am assigning a consecutive integer to each key, and passing this key to the function handleKeyPress. What I need inside this function is something that focuses the TextInput with key equal to i+1.

My code:

handleKeyPress(i, input_text) {
    // Here I need to focus the TextInput with key===(i+1)
    const text = this.state.text;
    text[i] = input_text;
    this.setState({
      text: text,
    });
}

render() {
    let ToRender = [];
    let n= 5;  // number of characters

    // First Input has autofocus set to true
    ToRender.push(
      <TextInput
        key={0}
        size="1"
        autofocus={true}
        value={this.state.text[0]}
        onChangeText={(text) => this.handleKeyPress(0, text)}
      />
    );

    // generate the rest of the Inputs
    for (let i=1; i<n; i++) {
      ToRender.push(
        <TextInput
          key={i}
          size="1"
          value={this.state.text[i]}
          onChangeText={(text) => this.handleKeyPress(i, text)}
        />
      );
    }

    return(
      <View style={styles.container}>
        {ToRender.map((e) => e)}
      </View>
    );
}

How can I focus a specific element given it's key?


Solution

  • Ok I managed to solve it.

    First, I have to reference the elements by the field ref instead of key, and access them using this.refs[i].focus() to focus the ith element:

    <TextInput
        key={i}
        ref={i}
        size="1"
        autofocus={true}
        value={this.state.text[i]}
        onChangeText={(text) => this.handleKeyPress(i, text)}
    />
    

    Then inside the function handleKeyPress I can do:

    handleKeyPress(i, input_text) {
        this.refs[i+1].focus();
    }