I'm working a react form using the controlled inputs to access the change on the form inputs. It contained lot of fields but i haven't posted all the fields.
import React from 'react';
import Links from './Links.jsx';
import axios from 'axios';
import Dialog from 'react-bootstrap-dialog';
import {Typeahead} from 'react-bootstrap-typeahead';
import Autocomplete from 'react-autocomplete';
import style from './app.css';
class AddNewEmployee extends React.Component {
constructor(props){
super(props);
this.state = {
firstName : '',
middleName : ''
}
this.handleUserInput = this.handleUserInput.bind(this);
}
handleUserInput(){
const name = e.target.name;
const value = e.target.value;
this.setState({
[name]: value
})
}
render() {
return(
<div className = "col-sm-6">
<input type="text"
placeholder="Enter First Name" name="firstName"
value={this.state.firstName} onChange={(event) => this.handleUserInput(event)}>
</input>
</div>
<div className = "col-sm-6">
<input type="text"
placeholder="Enter First Name" name="middleName"
value={this.state.middleName} onChange={(event) => this.handleUserInput(event)}>
</input>
</div>
)
}
}
export default AddNewEmployee;
The above code is working fine so far, but i got a requirement to keep an nested object to save the form input values.
But i'm missing some thing here how to handle the user input on form elements. How shall we handle the user input when we have a nested object.
import React from 'react';
import Links from './Links.jsx';
import axios from 'axios';
import Dialog from 'react-bootstrap-dialog';
import {Typeahead} from 'react-bootstrap-typeahead';
import Autocomplete from 'react-autocomplete';
import style from './app.css';
class AddNewEmployee extends React.Component {
constructor(props){
super(props);
this.state = {
employee : {
firstName : '',
middleName : ''
}
}
this.handleUserInput = this.handleUserInput.bind(this);
}
handleUserInput(){
// here how to handle those input changes
}
render() {
return(
<div className = "col-sm-6">
<input type="text"
placeholder="Enter First Name" name="firstName"
value={this.state.employee.firstName} onChange={(event) => this.handleUserInput(event)}>
</input>
</div>
<div className = "col-sm-6">
<input type="text"
placeholder="Enter First Name" name="middleName"
value={this.state.employee.middleName} onChange={(event) => this.handleUserInput(event)}>
</input>
</div>
)
}
}
export default AddNewEmployee;