How to declare dynamic state values in react

17,838

You can do the following:

const dynamicVar = 'test';

loop... {
    return <TextInput value={this.state[dynamicVar]} />
}

Edit: As your question is clearer, here is the updated answer

You should have This is a test in your input as value.

class Test extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <div>
        {list.map((item, index) => (
          <TextInput
            value = { this.state[item.id] }
            onChange = {(event) => this.setState({ [item.id]: event.target.value })}
          />
        )}
      </div>
    )
  }
}

Does it make sense or do you need more details ?

Share:
17,838

Related videos on Youtube

1110
Author by

1110

Updated on September 28, 2022

Comments

  • 1110
    1110 over 1 year

    I create text inputs in a loop.

    loop... {
        return <TextInput value={this.state.WHAT-TO-USE-HERE} />
    }
    

    As you can see I don't know how to dynamically set where text input will be in state?

    In JSX I have:

    render() { ...
      list.map((item, index) => {
       return this.createTextInput(item);
    ...
    

    Function that create inputs:

    createTextInput(item) {
      return (
        <TextInput value={this.state.XYZ} ... />
      )
    }