• Post category:React
  • Reading time:4 mins read

Date pickers are a common feature in web applications, providing a user-friendly way to select a date from a calendar. There are many libraries available for adding a date picker to React applications, but in this article, we will focus on the popular react-datepicker library.

To start using react-datepicker, you first need to install the library in your React application. This can be done using npm or yarn:

npm install react-datepicker

or

yarn add react-datepicker

Once the library is installed, you can import the DatePicker component and start using it in your React component. Here is a basic example of how to use the DatePicker component:

import React from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

const Example = () => {
  const [selectedDate, setSelectedDate] = React.useState(new Date());

  return (
    <DatePicker
      selected={selectedDate}
      onChange={date => setSelectedDate(date)}
    />
  );
};

export default Example;

In this example, we use the useState hook to manage the selected date in the selectedDate state. The DatePicker component is then used to render the date picker, and the selected date is passed as a prop to the component. The onChange prop is used to handle the change event and update the selectedDate state with the selected date.

It’s important to also import the styles for the react-datepicker library, as shown in the example, to ensure that the date picker is styled correctly.

There are many props available for customizing the appearance and behavior of the react-datepicker component. Here are some of the most commonly used props:

  • selected: This prop is used to set the selected date. It takes a Date object as a value.
  • onChange: This prop is used to handle the change event and update the selected date. It takes a callback function as a value, which receives the selected date as an argument.
  • minDate: This prop sets the minimum date that can be selected in the date picker.
  • maxDate: This prop sets the maximum date that can be selected in the date picker.
  • placeholderText: This prop sets the placeholder text for the input field.
  • todayButton: This prop sets the text for the button that selects today’s date.
  • withPortal: This prop determines whether the date picker should be rendered as a pop-up or not.

There are many more props available for customizing the react-datepicker component. You can find more information about these props in the official react-datepicker documentation.

In conclusion, adding a date picker to a React application is relatively straightforward using the react-datepicker library. With the wide range of props available for customizing the appearance and behavior of the date picker, you can create a user-friendly date picker that fits the needs of your application.

Leave a Reply