Skip to content Skip to sidebar Skip to footer

React-datepicker Years Range

I am using the react-datepicker package.https://reactdatepicker.com/ I am trying to create a custom date picker with a years range, following their example but I can not make the r

Solution 1:

Use below imports and all the code in documentation will work fine!

import { getMonth, getYear } from 'date-fns';
import range from "lodash/range";

Solution 2:

Functions getYear and getMonth are imported from date-fns library into react-datepicker/src/date_utils.js

enter image description here

I don't know about range function. I see it's being used in one example at their site (just a bunch of examples, no documentation) but there's nothing else.

You can simply import from date-fns (being a dependency of DataPicker) and create a range function.

import React, { useState } from "react";
import DatePicker from "react-datepicker";
import getYear from "date-fns/getYear";
import getMonth from "date-fns/getYear";
import "react-datepicker/dist/react-datepicker.css";

const Foo = () => {
  const [startDate, setStartDate] = useState(new Date());

  const range = (start, end) => {
    return new Array(end - start).fill().map((d, i) => i + start);
  };
  const years = range(1990, getYear(new Date()));
(...)

You can check a working demo here.


Post a Comment for "React-datepicker Years Range"