📅  最后修改于: 2023-12-03 15:19:45.185000             🧑  作者: Mango
react-datepicker
- Datepicker component for Reactreact-datepicker
is a customizable datepicker component for React. It provides a simple way to display a calendar with selectable dates, and supports various date format options.
You can install react-datepicker
using npm:
npm install react-datepicker
Import the DatePicker
component from react-datepicker
:
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
Then, render the DatePicker
component in your React application:
function App() {
const [startDate, setStartDate] = useState(null);
return (
<div>
<DatePicker selected={startDate} onChange={date => setStartDate(date)} />
</div>
);
}
By default, the datepicker will display the current date. To set a default date, you can pass an initial date value to the DatePicker
component using the selected
prop.
The onChange
prop allows you to handle changes to the selected date. When the user selects a date, the onChange
function will be called with the newly selected date as its argument.
react-datepicker
provides various props to customize its appearance and behavior. Here are some examples:
dateFormat
: A string representing the format of the selected date. See date-fns format for the list of available options.<DatePicker
selected={startDate}
onChange={date => setStartDate(date)}
dateFormat="yyyy-MM-dd"
/>
placeholderText
: The text to display in the input field when no date is selected.<DatePicker
selected={startDate}
onChange={date => setStartDate(date)}
placeholderText="Select a date"
/>
todayButton
: A boolean indicating whether to display a "Today" button that selects the current date.<DatePicker
selected={startDate}
onChange={date => setStartDate(date)}
todayButton="Today"
/>
disabled
: A boolean indicating whether the datepicker is disabled.<DatePicker
selected={startDate}
onChange={date => setStartDate(date)}
disabled={true}
/>
There are many more props available. See the documentation for a comprehensive list.
react-datepicker
is a useful and flexible datepicker component for React. With its customizable options and easy-to-use API, it's a great choice for any React project that needs to display and select dates.