react-flatpickr
react-flatpickr copied to clipboard
Easier way to handle allowInput blur value
Just figuring out a way to fire the onChange event when a user has entered a date into the input box and doesn't specifically press enter to lose the input focus - and I came up with this solution, but want to check, is there a better way?
import React from 'react'
import moment from 'moment'
import Flatpickr from 'react-flatpickr'
class FlatpickrWithBlur extends React.Component {
componentWillUnmount () {
const { handleBlur } = this
this.setState((prevState) => {
const { flatpickrNode } = prevState
// Make sure to remove the DOM listener when the component is unmounted.
if (flatpickrNode) {
flatpickrNode.removeEventListener('blur', handleBlur)
}
})
}
setFlatpickrRef = (reactFlatpickr) => {
const flatpickrNode = reactFlatpickr && reactFlatpickr.node
if (flatpickrNode) {
// add a DOM event listener
this.setState((prevState) => {
const { flatpickrNode: existingFlatpickrNode } = prevState
if (existingFlatpickrNode) {
// node already exists, don't attach another event handler
return null
}
flatpickrNode.addEventListener('blur', this.handleBlur)
return ({ flatpickrNode })
})
}
}
handleBlur = (event) => {
const { onChange } = this.props
const { target } = event
const { value } = target
// take the blur event and process the string value
const valueMoment = moment(value)
onChange([valueMoment.toDate(), valueMoment.toDate()])
}
render () {
return <Flatpickr {...this.props} ref={this.setFlatpickrRef} />
}
}
export default FlatpickrWithBlur
Unless I'm misunderstanding I believe you're looking for the onValueUpdate flatpickr event.
@jacobmischka nope, onValueUpdate is not fired for me when the form input loses focus.
I'm currently using onClose to handle blur events.
onClose does not work for inline
Thanks for creating a ticket. I am glad to be not the only one fighting with this issue. I solved it with a bit less code:
import Flatpickr from "react-flatpickr";
import german from "flatpickr/dist/l10n/de.js";
import react from "react";
class FlatpickrWithBlur extends react.Component {
constructor(props, context) {
super(props, context);
this.state = {
value: this.props.value
};
this.flatpickr;
}
render() {
return react.createElement(Flatpickr, {
ref: this.setFlatpickrRef.bind(this),
onChange: this.onChange.bind(this),
options: {
},
id: this.props.id
});
}
setFlatpickrRef(ref) {
if (ref && ref.node) {
this.flatpickr = ref;
}
}
componentDidMount() {
this.flatpickr.node.addEventListener("blur", this.handleBlur.bind(this));
}
componentWillUnmount() {
this.flatpickr.node.removeEventListener("blur", this.handleBlur.bind(this));
}
handleBlur(event) {
this.flatpickr.flatpickr.setDate(event.target.value, true);
}
onChange(value) {
this.setState({ value });
this.props.onChange(value);
}
}
export default FlatpickrWithBlur;