I'm going through documentation on React.js on this website and came across code that I was confused by.
From what I understand, the prefilled state of the isGoing checkbox will be true (hence checked) whereas the numberOfGuests is 2.
The part I get confused on is the handleInputChange() function which sets the variable target equal to event.target - it's a pre-built attribute that returns the DOM element that triggered the event. The value variable, allows for target.name to retrieve the name and assigns it to target.checked as a truthy and target.value as a falsy. The "target.checked" retrieves the current state of isOnGoing which is currently the boolean value true but what does "target.value" retrieve? Can someone explain that part to me?
Also, just to make sure that I'm understanding this properly: is the variable name equal to event.target.name or am I understanding this incorrectly?
Thanks for your help.
class Reservation extends React.Component {
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.name === 'isGoing' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<form>
<label>
Is going:
<input
name="isGoing"
type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of guests:
<input
name="numberOfGuests"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}