Source:  Twitter logo

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} ... />
  )
}

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 ?

16 users liked answer #0dislike answer #016
yuantonito profile pic
yuantonito

How about this (untested)

state={ change: {} }

handleChange = idx => {

this.setState(change[idx]: e.target.value )
}

loop... {
    return <TextInput onChange={()=> handleChange(idx)} value={this.state.change.idx} />
}
-2 users liked answer #1dislike answer #1-2
livehappydrinkcoffee profile pic
livehappydrinkcoffee

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).