React-Datetime; I’m using two in one component, how do I tell which is which?

This is an odd question about react-datetime: Why doesn’t the callback allow a “name” to be returned?

I’m using Daytime twice for “start” and “end” times on a calendar scheduler. But I want to use a single “onChange” event to update state. The problem is: Datetime onChange only returns the time, it doesn’t return a name or an ID or any way for me to identify which Datetime component is sending the onChange.

Here is the render() code:

<CardSubtitle>Start Date:
  <Datetime 
    value = {this.state.start}
    onChange={this.handleChange}
    className = "dateTimeModule"
  />
</CardSubtitle>

<CardSubtitle>End Date:
  <Datetime 
    value = {this.state.end}
    onChange={this.handleChange}
    className = "dateTimeModule"
  />
</CardSubtitle>

And here is the logic I want to use:

handleChange = (e) => {

  this.setState({
    bodyEdit: true,
    [e.target.name]:e.target.value
  })
};

But “e” only contains the date object. It appears that Datetime doesn’t support a “name” return?

I’m confused, it seems like an obvious miss. How do I differentiate between these? Do I need to write separate functions for each?

Thinking about doing this:

handleStartChange = (e) => {
  this.setState({
    startDate: e
  })
};

handleEndChange = (e) => {
  this.setState({
    endDate: e
  })
};

But this seems like unnecessary code.

Answer

What you can do is pass yourself an additional parameter to your function:

        <CardSubtitle>Start Date:
          <Datetime 
            value = {this.state.start}
            onChange={(e) => this.handleChange(e, "start")}
            className = "dateTimeModule"
          />
        </CardSubtitle>

        <CardSubtitle>End Date:
          <Datetime 
            value = {this.state.end}
            onChange={(e) => this.handleChange(e, "end")}
            className = "dateTimeModule"
          />
        </CardSubtitle>

and reuse this parameter in your handleChange(e, name) function:

  handleChange = (e, name) => {
    this.setState({
      bodyEdit: true,
      [name]:e
    })
  };

Also make sure of what is returned by the library you are using as the “e”, it doesn’t seem to be a classical event but rather a moment object:

Callback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).

Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .