Scenario:
You have an input field on a page, and whatever number user puts in, I want to generate that much more inputs. Each input generated represents values that user can choose. By default, we generate values from 0 -> N.
Example: if user sets input to 5 we would generate 5 inputs, each having values from 0 -> 4
Problem:
The values we generate by default might change. For example, user maybe wants to change one of the inputs to his value.
Example: Users sets 5, we generate 5 inputs, from 0 -> 4, then he decides that we wants to change one of the values to 42. In that case, we would have, for example:
input1: 0
input2: 1
input3: 3
input4: 42
Question
I want/need to have this values in state because otherwise I can not update the value as they type into the inputs.
The problem I am facing is: how can I know which one he is typing into? The inputs are generated dynamically.
If I set inputs to have a inputChangeHandler() what to check inside that function to know which state value to change? Also, since other values need to be preserved, I only need to change that key, not others.. Lots of issues I am facing as you see. :) Any advice would be appreciated.
Demo
Editor: https://stackblitz.com/edit/react-gaq7eh
Live: https://react-gaq7eh.stackblitz.io (input is in the top left corner)
P.S - not sure if editor changes reflect everywhere, so just in case, here's the code:
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
class InputProblem extends React.Component {
constructor() {
super();
this.state = {
inputs: [],
inputValue: null
};
}
generateInputs = (value) => {
this.setState({inputs: Array.from(Array(Number(value)).keys()), inputValue: Number(value)})
}
render() {
return (
<div>
<input className="main-input" type="text" value={this.state.inputValue} onChange={(e) => this.generateInputs(e.target.value)} />
{
this.state.inputs.map(item => (
<input type="text" value={item}/>
))
}
</div>
)
}
}
render(<InputProblem />, document.getElementById('root'));