1

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?

4
  • I'd suggest storing the metadata in state, and then using that to generate the components in render(), as oppose to storing components in state. Commented Jan 2, 2017 at 20:13
  • @lux Thanks, I'll do that, I'm new to React. But I don't see how it solves me issue. Or did you just give me an advice? Commented Jan 2, 2017 at 20:18
  • As a best practice... jsx should be written inside the render method. Commented Jan 3, 2017 at 7:13
  • @KhalidAzam Thanks, I took a note of it. Commented Jan 3, 2017 at 16:57

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That's exactly what I wanted, didn't think of passing index to onChange function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.