haoxins / react-flatpickr

flatpickr for React
MIT License
599 stars 101 forks source link

Easier way to handle allowInput blur value #84

Open timkrins opened 5 years ago

timkrins commented 5 years ago

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
jacobmischka commented 5 years ago

Unless I'm misunderstanding I believe you're looking for the onValueUpdate flatpickr event.

timkrins commented 5 years ago

@jacobmischka nope, onValueUpdate is not fired for me when the form input loses focus.

RigoOnRails commented 5 years ago

I'm currently using onClose to handle blur events.

mtinner commented 4 years ago

onClose does not work for inline

adymorz commented 4 years ago

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:

((Code removed))

adymorz commented 3 weeks ago

I updated to react-flatpickr version 3.10.13 which is based on flatpickr version 4.6.13.

The workaround I created four years ago does not work any more, but @timkrins's still does, so I deleted my comment from four years ago.