Search code examples
reactjsreact-datepicker

react date-picker not set the date


I am using react date-picker library in my project. Currently date-picker is loading correctly. But when I select a date - it did not set to textbox. How do I set selected date for my textbox?.

This is my code

  <DatePicker
     className="form-control form-control-sm"
     type="text"
     size="sm"
     placeholder=""
     onChange={handleChange}
     value={values}
  />

 const handleDateChange = (date) => {
    alert(date);
 };

How do I set selected date?


Solution

  • I think the reason why it does not set the date to you is because you are using the DatePicker wrong.

    You are defining a handleDateChange function but you are not using that anywhere. Then you are using handleChange function in DatePicker but I assume it is not defined as you haven't provided the code for it. Next, you are setting value to values which as well I assume is undefined due to the lack of code provided.

    However, I can give you a hint.

    To use the DatePicker, you need to provide a date to the selected attribute so that it can select the date (e.g. today's date). Also, if you want to store that date, you need to create a state for it so you can use it later on. Finally, you need to define a function before calling DatePicker that will handle the setting of the new date in your state. If you do this, you will have a working DatePicker. I have also provided you with a small example of how to use DatePicker. I also recommend reading the documentation of the "react-datepicker" where you will find most of this information and more.

    import React, { useState } from "react";
    import DatePicker from "react-datepicker";
    import "react-datepicker/dist/react-datepicker.css";
    
    export default function App() {
      const [date, setDate] = useState(new Date());
    
      const handleChange = (date) => {
        setDate(date);
      };
    
      return (
        <div>
          <DatePicker
            className="form-control form-control-sm"
            type="text"
            size="sm"
            placeholder=""
            selected={date}
            onChange={handleChange}
          />
        </div>
      );
    }