简体   繁体   中英

how to use react-datepicker

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>
  );
}

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

That should resolve your issue!

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

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>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM