Home > database >  how to use react-datepicker
how to use react-datepicker

Time:06-26

I'm trying to add a datepicker using react-datepicker but when I tried it in codesandbox, I got this error message:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

even though I already put import { DatePicker } from "react-datepicker"; and add the react-datepicker package in the dependency list.

here's my code:

import { useState } from "react";
import { DatePicker } from "react-datepicker";

export default function App() {
  const [startDate, setStartDate] = useState(new Date());

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <div>
        <DatePicker
          selected={startDate}
          onChange={(date) => setStartDate(date)}
        />
      </div>
    </div>
  );
}

CodePudding user response:

In Line 2, change to: import DatePicker from "react-datepicker";

That should resolve your issue!

CodePudding user response:

Here's an example. In this one, we select a month from datepicker.

import React, { useCallback, useState } from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

const YourComponent = () => {
  const [date, setDate] = useState<Date>(null);
  
  const onDateChangeHandler = useCallback(date => setDate(date), [date]);

  return (
    <div className="position-relative">
      <DatePicker
        className="form-control w-100 text-center"
        placeholderText="Select date"
        selected={date}
        onChange={onDateChangeHandler}
        dateFormat="MM/yyyy"
        showMonthYearPicker
        showFullMonthYearPicker
        showTwoColumnMonthYearPicker
        dropdownMode="select"
      />
    </div>
  );
};

Further reading

React DatePicker

CodePudding user response:

i have made some changes in code try this it should work.

import { useState } from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

export default function App() {
  const [startDate, setStartDate] = useState(new Date());

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <div>
        <DatePicker
          selected={startDate}
          onChange={(date) => setStartDate(date)}
        />
      </div>
    </div>
  );
}
  • Related