Reputation: 3433
I am using react-typescript for my app. I am using React-datepicker package. I want to create one global date range component. So I can reuse it to the different component. I have used React-datepicker's customInput
for styling and created buttons where it display the time. I followed this link for date range logic. In the calendar date range seems work and this is the image. I want to display choosing start date and end date in the customInput's
button. But as soon as I choose the end date, both buttons display the end date's value. I don't know how to fix it.
This is date range component
import React, { useState } from "react";
import DatePicker, { ReactDatePickerProps } from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import moment from "moment";
import { Button } from "components/buttons";
export interface IDatepicker {
value: {
start: Date;
end: Date;
};
onBlur?: (i: React.FocusEvent<HTMLInputElement>) => void;
onFocus?: (i: React.FocusEvent<HTMLInputElement>) => void;
onChange: (i: Date) => void;
buttonComponent?: JSX.Element;
withPortal?: boolean;
showTimeSelect?: boolean;
dateFormat?: string;
timeFormat?: string;
}
export default ({
value,
onChange,
onBlur,
onFocus,
buttonComponent,
withPortal = false,
showTimeSelect = false,
dateFormat = "MMMM d, yyyy h:mm aa",
timeFormat = "HH:mm"
}: IDatepicker) => {
const handleChange = (date: Date | null) => {
date && onChange(date);
};
return (
<div style={{ display: "flex" }}>
<DatePicker
selected={value.start}
onChange={handleChange}
showTimeSelect={showTimeSelect}
selectsStart
startDate={value.start}
endDate={value.end}
customInput={
<Button>
{moment(value.start)
.format("MMMM Do YYYY")
.toString()}
</Button>
}
/>
<div style={{ color: "black" }}>-</div>
<DatePicker
selected={value.end}
onChange={handleChange}
showTimeSelect={showTimeSelect}
selectsEnd
startDate={value.start}
endDate={value.end}
minDate={value.start}
customInput={
<Button>
{moment(value.end)
.format("MMMM Do YYYY")
.toString()}
</Button>
}
/>
</div>
);
};
This is the component i am using the date range component
import React from "react";
import TimeLine from "components/datepicker";
export default () => {
const [state, setState] = useState(new Date());
return (
<div>
<TimeLine
value={{ start: state, end: state }}
onChange={setState}
/>
</div>
);
};
Upvotes: 3
Views: 9119
Reputation: 1635
You are using single state value for both start and end. I think that's the root cause of your issue. Instead of using
const [state, setState] = useState(new Date());
I think you should declare it as
const [startDate, setStartDate] = useState(new Date());
const [endDate, setEndDate] = useState(new Date());
Upvotes: 1