I am using react-datepicker
https://reactdatepicker.com/ and I want to achieve something like below.
So I will have one input field which will allow me to select a Date of Birth and if user clicks on that input field then first it should ask user to select a Year, after they select a year, in the same dialog box it will ask to select a Month and after they select Month, it should ask a Date.
I am trying below code without any success.
Currently what is happening, Once I click on date input, its asking me to select a year but as soon as I select a Year .. its getting closed .. it should not happen .. Then if i click again.. its asking me to select a Month which is correct .. but again dialog box getting closed .. and if I click again , I can not see Dates selection .. instead its showing same “Months” list.
Can someone guide me what I am doing wrong here .. Below is my full code ..
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
const [startDate, setStartDate] = useState(null);
const [selectedStep, setSelectedStep] = useState("year");
const handleYearSelect = (date) => {
setStartDate(date);
setSelectedStep("month"); // Switch to the month picker
};
const handleMonthSelect = (date) => {
setStartDate(date);
setSelectedStep("day"); // Switch to the day picker
};
const handleDaySelect = (date) => {
setStartDate(date); // Final date selection
};
const CustomInput = ({ value, onClick }) => (
<input
type="text"
value={value}
onClick={onClick}
placeholder={`Select ${
selectedStep === "year"
? "Year"
: selectedStep === "month"
? "Month"
: "Date"
}`}
readOnly
/>
);
const dateFormat =
selectedStep === "year"
? "yyyy"
: selectedStep === "month"
? "MM/yyyy"
: "MM/dd/yyyy";
<DatePicker
selected={startDate}
onChange={handleYearSelect}
dateFormat={dateFormat}
showYearPicker={selectedStep === "year"}
showMonthYearPicker={selectedStep === "month"}
showMonthPicker={selectedStep === "day"}
customInput={<CustomInput />}
/>
I want to achieve this using only single <DatePicker />
.
Can someone please help me.