I have got Django Rest Framework backend and I am trying to post data there via React. Fetching the data is working fine. If I tried to post data with only one input it also worked fine. But when I try add more inputs, it does not work and I dont know how to handle multiple inputs..
React Code:
class Activity2project extends React.Component {
constructor(props) {
super(props);
this.state = {
virtualProjectList:[],
activeItem:{
id:null,
project_name:'',
project_name_RnD:'',
},
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
this.fetchVirtualProjects = this.fetchVirtualProjects.bind(this)
}
handleChange(e){
var name = e.target.name
var value = e.target.value
this.setState({
activeItem:{
...this.state.activeItem,
project_name:e.target.value,
project_name_RnD:e.target.value,
}
})
}
render(){
<div>
<input onChange={this.handleChange} type='text' id='virtual_project' name='virtual_project_name' value={this.state.activeItem.project_name} placeholder='Project Name' ></input>
<input onChange={this.handleChange} type='text' id='virtual_project_RnD' name='virtual_project_name_RnD' value={this.state.activeItem.project_name_RnD} placeholder='Project Name RnD' ></input>
<input id='submit' type='submit' name='Add'></input>
</div>
}
With this it writes the same value into inputs and I dont now how to distinguish these two inputs.
you can give your input fields ids that matches the attributes of your state:
<input onChange={this.handleChange} type='text' id='project_name' name='virtual_project_name' value={this.state.activeItem.project_name} placeholder='Project Name' ></input>
<input onChange={this.handleChange} type='text' id='project_name_RnD' name='virtual_project_name_RnD' value={this.state.activeItem.project_name_RnD} placeholder='Project Name RnD' ></input>
and then in changeHandler
:
let id = event.target.id;
// then using computed property name
activeItem: {
...this.state.activeItem,
[id]: event.target.value
}
});