Closed jayehernandez closed 1 year ago
Updating the picker value in Vanilla JavaScript seems to work fine. Haven't tried it with React so far. Not sure what causes it in your example, but I'll look into it.
This seems to be a workaround for now:
import { defineCustomElements } from "wc-datepicker/dist/loader";
import { useState, useEffect, useRef } from "react";
import "wc-datepicker/dist/themes/light.css";
defineCustomElements();
function DateInput() {
const [value, setValue] = useState("");
const datepicker = useRef();
useEffect(() => {
function updateValue(e) {
const currentDate = e.target.value;
const year = currentDate.getFullYear(); // get the year component
const month = currentDate.getMonth() + 1; // get the month component (adding 1 because January is 0)
const day = currentDate.getDate(); // get the day component
const dateString = `${year}-${month
.toString()
.padStart(2, "0")}-${day.toString().padStart(2, "0")}`;
setValue(dateString);
}
datepicker.current.addEventListener("selectDate", updateValue);
return () =>
datepicker.current.removeEventListener("selectDate", updateValue);
});
useEffect(() => {
datepicker.current.value = value ? new Date(value) : undefined;
}, [value]);
return (
<>
{value}
<br />
<input
type="date"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<br />
<wc-datepicker
id="datepicker"
start-date={value ? new Date(value) : undefined}
ref={(el) => (datepicker.current = el)}
></wc-datepicker>
</>
);
}
export default DateInput;
I've also moved the defineCustomElements
call out of the component declaration. This function should only be called once. Also, resetting the start-date on each value change should not be necessary.
Thanks for the help @Sqrrl, appreciate it. I'll use this workaround for now. Great project, btw!
Hey! I'm trying to bind the same value to both a date input field and the picker. Clicking on a value in the picker updates the date input field, but not the other way around. I can see though that the calendar itself gets updated (if for example, the month changes), but the date is not selected in the calendar. Is there something I'm missing? Thanks!
Sample code