Search code examples
react-nativekeytextinput

React-Native: Access to key prop in TextInput


I try to access the key prop in TextInput to save it in the state (and then in Redux). I create in an array so many TextInput fields as I got from my first screen:

render() {
    const { playerAmount } = this.props;
    var textBoxes = [];
    for (var i = 0; i < playerAmount; i++) {
      var placeholderText = 'Player ' + (i + 1);
      textBoxes.push(
        <TextInput
          key = {i+1}
          onChangeText={(text) => {
            const Player = Object.assign({}, this.state.Player, { playerName: text, playerNumber: this.props.key});
            this.setState({ Player });
          }}
          placeholder={placeholderText}
          placeholderTextColor="grey"
        >
        </TextInput>

      );

Now I try to set the state of the playerNumber with the key prop. I tried it with key / {key} / this.props.key

Constructor:

  constructor(props) {
    super(props);
    this.state = 
    {
      Player: 
      {
        playerName: "",
        playerNumber: 0
      }
    }

  }

As you can see I am pretty new to React-Native. Do you have any idea how to solve this?

Thank you so much! :)


Solution

  • Why not just do this?

    render() {
      const { playerAmount } = this.props;
      var textBoxes = [];
      for (var i = 0; i < playerAmount; i++) {
        var placeholderText = 'Player ' + (i + 1);
        const key = i+1;
        textBoxes.push(
              <TextInput
                  key = {key}
                  onChangeText={(text) => {
                    const Player = Object.assign({}, this.state.Player, { playerName: text, playerNumber: key});
                    this.setState({ Player });
                  }}
                  placeholder={placeholderText}
                  placeholderTextColor="grey"
              >
              </TextInput>
        );
      }
    }