Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date picker month / year doesn't work on iOS

I am using react-day-picker package to select a date with the year/month props included. However, the year/month dropdown doesn't work properly on iOS mobile browsers:

import React from 'react';
import ReactDOM from "react-dom";
import DayPickerInput from 'react-day-picker/DayPickerInput';
import 'react-day-picker/lib/style.css';

const currentYear = new Date().getFullYear();
const fromMonth = new Date(currentYear, 0);
const toMonth = new Date(currentYear + 10, 11);

function YearMonthForm({ date, localeUtils, onChange }) {
  const months = localeUtils.getMonths();

  const years = [];
  for (let i = fromMonth.getFullYear(); i <= toMonth.getFullYear(); i += 1) {
    years.push(i);
  }

  const handleChange = function handleChange(e) {
    const { year, month } = e.target.form;
    onChange(new Date(year.value, month.value));
  };

  return (
    <form className="DayPicker-Caption">
      <select name="month" onChange={handleChange} value={date.getMonth()}>
        {months.map((month, i) => (
          <option key={month} value={i}>
            {month}
          </option>
        ))}
      </select>
      <select name="year" onChange={handleChange} value={date.getFullYear()}>
        {years.map(year => (
          <option key={year} value={year}>
            {year}
          </option>
        ))}
      </select>
    </form>
  );
}

export default class Example extends React.Component {
  constructor(props) {
    super(props);
    this.handleYearMonthChange = this.handleYearMonthChange.bind(this);
    this.state = {
      month: fromMonth,
    };
  }
  handleYearMonthChange(month) {
    this.setState({ month });
  }
  render() {
    const dayPickerProps = {
      month: this.state.month,
      fromMonth: fromMonth,
      toMonth: toMonth,
      captionElement: ({ date, localeUtils }) => (
        <YearMonthForm
          date={date}
          localeUtils={localeUtils}
          onChange={this.handleYearMonthChange}
        />
      )
    };

    return (
      <div className="YearNavigation">
        <DayPickerInput
          showOverlay={true}
          dayPickerProps={dayPickerProps}
        />
      </div>
    );
  }
}
ReactDOM.render(<Example />, document.getElementById("root"));

You can see the demo on this link (must open it on an iOS device):

https://codesandbox.io/s/0y84wrp8mn

Any workaround for this?

like image 262
catandmouse Avatar asked Mar 14 '19 06:03

catandmouse


1 Answers

the problem is the default keepFocus is set to true. Change your render method like that in your Example Component (keepFocus={false}):

return (
  <div className="YearNavigation">
    <DayPickerInput
      showOverlay={true}
      keepFocus={false}
      dayPickerProps={dayPickerProps}
    />
  </div>
);
like image 111
di3 Avatar answered Oct 05 '22 17:10

di3