I am working on multiple checkboxes on my site. This is the my state
state = {
data: {
airport_transport: false,
night_club: false,
wifi: false,
parking: false,
swimming_pool: false,
restaurant: false,
gym: false,
air_conditioner: false,
laundry_services: false,
bar_lounge: false,
disabled_services: false,
elevator: false,
shuttle_bus_service: false,
cards_accepted: false,
},
errors: {},
};
This is how i am handling the state of the checkboxes. I am posting only few handle methods
toggleChangeShuttle = () => {
let data = this.state.data;
data.shuttle_bus_service = !data.shuttle_bus_service;
this.setState({ data });
};
toggleChangeAirport = () => {
let data = this.state.data;
data.airport_transport = !data.airport_transport;
this.setState({ data });
};
toggleChangeCooling = () => {
let data = this.state.data;
data.air_conditioner = !data.air_conditioner;
this.setState({ data });
};
toggleChangeNightClub = () => {
let data = this.state.data;
data.night_club = !data.night_club;
this.setState({ data });
};
And finally this is how i am rendering. I am omitting extra render methods
<div className="form-check">
<label className="container">
<input
type="checkbox"
checked={this.state.data.air_conditioner}
onChange={this.toggleChangeCooling}
className="form-check-input"
/>
<span className="checkmark"></span>
Air Conditioner
</label>
</div>
<div className="form-check">
<label className="container">
<input
type="checkbox"
checked={this.state.data.airport_transport}
onChange={this.toggleChangeAirport}
className="form-check-input"
/>
<span className="checkmark"></span>
Airport Transport
</label>{" "}
</div>
<div className="form-check">
<label className="container">
<input
type="checkbox"
checked={this.state.data.bar_lounge}
onChange={this.toggleChangeBarLounge}
className="form-check-input"
/>
<span className="checkmark"></span>
Bar Lounge
</label>{" "}
</div>
Now this looks manual with lots of repetitions. Is there a compact clean way to do this? Thanks
Aucun commentaire:
Enregistrer un commentaire