Nick
Nick

Reputation: 17

How to correctly take a Date object passed with state in React into datepicker?

I'm using DatePicker with my react app. I pass an object which contains a date field from one component to another via location.state. This is an editing component, where I can change the values of these fields. But the console swears with invalid time exception. I read I should do something with parseISO but still it does nothing. How to properly use it? (settings is a this.state field)

...
import DatePicker from 'react-datepicker'
import 'react-datepicker/dist/react-datepicker.css'
import { parseISO, format } from 'date-fns'
...

            <DatePicker
              name="saleDateFrom"
              selected={parseISO(settings.saleDateFrom)}
              onChange={this.handleChangeFrom}
              dateFormat="MMMM dd, yyyy hh:mm:ss aa"
            />

Upvotes: 0

Views: 171

Answers (2)

   <DatePicker
          name="saleDateFrom"
          selected={new Date(settings.saleDateFrom)}
          onChange={this.handleChangeFrom}
          dateFormat="MMMM dd, yyyy hh:mm:ss aa"
        />

This will take care of your issues. react-datepicker expects date as javascript Date objects

Upvotes: 1

Jacob
Jacob

Reputation: 926

You can use Date.parse(settings.saleDateFrom) to get the time since epoch.

If you need it as a data object.

new Date(Date.parse(settings.saleDateFrom))

Upvotes: 1

Related Questions