Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Datepicker handleChange with multiple name attributes

Tags:

I have 6 form inputs that are using React-Datepicker. I need to use handleChange() to setState 6 times, but I do not understand how to get the name attribute dynamically from each form input because 'date' doesn't contain any other data when passing it through the function. I've tried passing 'name', but it doesn't work. The same goes for handleSelect()

this.state = {
  dateOne: new Date(),
  dateTwo: new Date(),
  dateThree: new Date(),
  dateFour: new Date(),
  dateFive: new Date(),
  dateSix: new Date()
}

handleChange(date) {
  this.setState({ ...this.state, ?????: date });
}

handleSelect(date) {
  this.setState({ ...this.state, ?????: date });
}

<form>
  <DatePicker
    name="dateOne"
    selected={this.state.dateOne}
    onSelect={this.handleSelect}
    onChange={this.handleChange}
  />
  <DatePicker
    name="dateTwo"
    selected={this.state.dateTwo}
    onSelect={this.handleSelect}
    onChange={this.handleChange}
  />
  <DatePicker
    name="dateThree"
    selected={this.state.dateThree}
    onSelect={this.handleSelect}
    onChange={this.handleChange}
  />
 <DatePicker
    name="dateFour"
    selected={this.state.dateFour}
    onSelect={this.handleSelect}
    onChange={this.handleChange}
  />
  <DatePicker
    name="dateFive"
    selected={this.state.dateFive}
    onSelect={this.handleSelect}
    onChange={this.handleChange}
  />
  <DatePicker
    name="dateSix"
    selected={this.state.dateSix}
    onSelect={this.handleSelect}
    onChange={this.handleChange}
  />
</form>

I've also tried this: https://github.com/Hacker0x01/react-datepicker/issues/242 without any luck.

Any help would be awesome!

like image 299
Matthew Avatar asked Dec 06 '18 22:12

Matthew


1 Answers

You can try like this:

<DatePicker
    name="dateOne"
    selected={this.state.dateOne}
    onSelect={this.handleSelect}
    onChange={(date)=>this.handleChange(date, 'dateOne')} //pass name as string
  />

handleChange(date, name) {
    this.setState({
        [name]: data
    });
}

So you pass the name as string, since you can't access target.name and then update state by name you receive [name]

like image 153
Ertan Hasani Avatar answered Oct 05 '22 00:10

Ertan Hasani