Search code examples
reactjsdatetimematerial-uireact-datetime

Setting state with the value of a react-dateTime component


please I need help. I'm using a react-dateTime component, and I am simply trying to get the value of that component just like every other field in a form. But I am unable to get the value of the selected date let alone store it in a state with the other attributes on other fields.

Here is my code:

Datetime component

  <Datetime
    onChange={this.handleChange}
    value={startDate}
    timeFormat={true}
    name="startDate"
    inputProps={{ placeholder: "Start Date" }}
   />

event handler

  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

second onchange handler

 handleSelectDate = event => {
    if (event.target.name === "startDate") {
      this.setState({ startDate: event.target.value});
    } else {
      this.setState({ endDate: event.target.value });
    }
  }```

The state object

 this.state= { startDate: '' }

I have tried different approaches, currently I get an error that event.target is undefined, so there is no event at all, I have also tried to initialize the handler by calling event there onChange

Thanks


Solution

  • It doesn't work like regular input to get its value by name

    onChange: 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). Docs

    Try this:

    class App extends React.Component {
    
      state = {
        startDate: ""
      }
      // You need to bind "this"
      handleChange = this.handleChange.bind(this)
    
      // Receives the selected "moment" object as only parameter
      handleChange(date) {
        this.setState({ startDate: date })
      }
    
      render() {
        return (
          <div>
            <Datetime
              value={this.state.startDate}
              onChange={this.handleChange}
              timeFormat={true}
              inputProps={{ placeholder: "Start Date" }}
            />
            <hr />
            Select date:{" "}
            {this.state.startDate ? this.state.startDate.toString() : "no selected date"}
          </div>
        )
      }
    }
    

    Check this codeSandbox example.

    Although it works, it's kinda outdated and I encourage you to check react-datetime-picker or react-date-picker