Reputation: 602
I am using the react-day-picker library to display a date picker on my site. I would like to listen for when the date has been changed. I know there are onDayChange hooks you can add to the DayPickerInput
components, but I want to listen for a change outside of the component.
Example: (https://codesandbox.io/s/react-day-picker-base-mpcqy)
import React from "react";
import ReactDOM from "react-dom";
import DayPickerInput from "react-day-picker/DayPickerInput";
import "react-day-picker/lib/style.css";
function Example() {
return (
<div>
<h3>DayPickerInput</h3>
<DayPickerInput placeholder="DD/MM/YYYY" format="DD/MM/YYYY" />
</div>
);
}
ReactDOM.render(<Example />, document.getElementById("root"));
var input = document.getElementsByTagName("input")[0];
input.addEventListener("change", () => {
console.log("changed");
});
I would expect the on change handler to be fired. I'm not sure why it isn't. How can I listen to the value change?
Upvotes: 2
Views: 2172
Reputation: 2943
You can see answer of your question in react-day-picker
documentations
You should pass event handler to your DayPickerInput
component this way:
function Example() {
const [value, setValue] = useState(undefined);
handleDayChange(day) {
setValue(day);
}
return (
<div>
<h3>DayPickerInput</h3>
<DayPickerInput
placeholder="DD/MM/YYYY"
format="DD/MM/YYYY"
onDayChange={day => handleDayChange(day)}
/>
</div>
);
}
This is the only method to listen to an event. Also you should know that it's very bad practice to mutate DOM directly.
And if you want to make value
accessible globally, you should use React's context API or Redux. (State management tool)
Upvotes: 4