Red Baron
Red Baron

Reputation: 7682

Why is my React Dates component not working?

Can't seem to work out how to fix React Dates without breaking something different each time

I have this:

const [startDate, setStartDate] = useState(moment().subtract(2, 'year'))
const [endDate, setEndDate] = useState(null)
const [focusedInput, setFocusedInput] = useState('startDate')



const onDatesChange = ({ startDate, endDate }) => {
    setStartDate(startDate)
    setEndDate(endDate)
}


<DateRangePicker
    endDate={endDate}
    endDateId="endDate"
    focusedInput={focusedInput.focusedInput}
    isOutsideRange={() => null}
    onDatesChange={onDatesChange}
    onFocusChange={(focusedInput) => setFocusedInput({ focusedInput })}
    startDate={startDate}
    startDateId="startDate"
/>

so first error I get is this: Uncaught Error: Objects are not valid as a React child (found: object with keys {_isAMomentObject, _isUTC, _pf, _locale, _d, _isValid})

so then I've tried various things like this:

const onDatesChange = ({ startDate, endDate }) => {
    setStartDate(moment(startDate).format('DD-MM-YYYY')
    setEndDate(moment(endDate).format('DD-MM-YYYY)
}

and setting the initial state to null. but then that gave me an invalid date error

All I want to do is set 2 different dates in a range and it seems incredibly complicated

Upvotes: 0

Views: 1012

Answers (1)

chandan_kr_jha
chandan_kr_jha

Reputation: 557

I found the comment on the github page here github You have to import react-dates/initialize

import React, { useState } from "react";
import "./styles.css";
import moment from "moment";
import "react-dates/initialize";
import { DateRangePicker } from "react-dates";
import "react-dates/lib/css/_datepicker.css";

export default function App() {
  const [startDate, setStartDate] = useState(moment().subtract(2, "year"));
  const [endDate, setEndDate] = useState(null);
  const [focusedInput, setFocusedInput] = useState("startDate");

  const onDatesChange = ({ startDate, endDate }) => {
    setStartDate(startDate);
    setEndDate(endDate);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <DateRangePicker
        endDate={endDate}
        endDateId="endDate"
        focusedInput={focusedInput.focusedInput}
        isOutsideRange={() => null}
        onDatesChange={onDatesChange}
        onFocusChange={focusedInput => setFocusedInput({ focusedInput })}
        startDate={startDate}
        startDateId="startDate"
      />
      ;
    </div>
  );
}

Refer this sandbox link also. https://codesandbox.io/s/hidden-currying-9jydi?file=/src/App.js

Upvotes: 2

Related Questions