Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js dynamic input field value to state

Tags:

reactjs

How to pass dynamic input field value to state as an array and update the value when user changes the input again?

Input field was generated by JSON data and in the state, we cannot define the initial value for all. Can anyone give some advice for this kind of problem?

this.state = { 
file:[{value1,value2}]
}; 

and input field is generated like

{this.state.language.map((item,index) =>
<div className="be-checkbox inline" key={index} >
 <input type="text"  onChange={this.handleChange.bind(this, index)} value={this.state.index} />
</div>
)}
like image 526
Dinesh Ghimire Avatar asked Dec 10 '25 12:12

Dinesh Ghimire


2 Answers

Add onChange and value in every input like below.

<input type="text" onChange={this.handleChange.bind(this, index)} value={this.state.index}/>

Add the function to be called

handleChange(name, e){
    var change = {};
    change[name] = e.target.value;
    this.setState(change);
  }
like image 68
S.M. Shakil Avatar answered Dec 12 '25 09:12

S.M. Shakil


Using React Hooks:

const [data, setData] = useState({});
//create an onInputChange function for the inputs this way
const onInputChange = async e => {
  const {name, value} = e.target;
  //check to validate if entry is not a number
  if(isNaN(name)){
    data[name] = value;
    
    //somehow update data
    setData({...data})
  }
}
like image 25
Vicheans Avatar answered Dec 12 '25 09:12

Vicheans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!