Chris Kraszewski
Chris Kraszewski

Reputation: 690

setState() of specific array item

I'm generating multiple inputs and want to bind their values to array stored in state. I'm using an array because the number of inputs varies and I can't create them statically. I'm assigning their value and it works as expected:

    this.setState({
      wordInputs: this.state.userTitle.map((word) => {
      let input = <input type="text" key={i} value={this.state.userTitle[i]} onChange={this.checkWordInput}/>
      i++
      return input
      })
    })

Now I want to handle user input with checkWordInput() and here comes my question: how do I access input's key property set earlier in order to update the this.state.userTitle array? Or is there a different way to do this?

Upvotes: 1

Views: 2522

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

I think you don't need store inputs in state, you can move inputs to render, like so

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      userTitle: [
        'title - 1',
        'title - 2',
        'title - 3',
        'title - 4'
      ]
    };
    
  }
  
  checkWordInput(index, e) {
    this.setState({
      userTitle: this.state.userTitle.map((title, i) => (
        i === index ? e.target.value : title
      ))
    })  
  }
        
  render() {
    const inputs = this.state.userTitle.map((title, index) => ( 
      <input 
        type="text" 
         key={index} 
         value={title} 
         onChange={ (e) => this.checkWordInput(index, e) }
      />
    ));
        
    return (
      <form>
        { inputs }

        { this.state.userTitle.map((title, i) => <p key={i}> { title }</p>) }
      </form>
    );
  }          
}
        
ReactDOM.render(
  <App />, 
  document.getElementById('app')
);

        
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Upvotes: 2

Related Questions