0

I am trying to use DayPickerInput with my own custom input, however when typing the input loses focus as soon as a day is selected. This can be seen if trying to type for example: 2020-08-20, when the input gets to '2020-08-2' it selects the 2nd as a date and unfocuses the input, not allowing the user to get to 20.

Here is a code sandbox where I have replicated the problem.

The usage of DayPickerInput:

<DayPickerInput
        component={(props) => <CustomInput {...props} />}
        value={value}
        onDayChange={setValue} />

And my custom input component:

import React from "react";

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  focus() {
    this.inputRef.current.focus();
  }

  render() {
    return <input {...this.props} ref={this.inputRef} />;
  }
}

export default Input;

I have seen this issue, and tried what was explained there, but it does not work and I am not sure what else to try.

Any guidance is appreciated! Thanks!

Lara
  • 516
  • 1
  • 3
  • 9
  • can you try to add "hideOnDayClick={false}" as a prop to the DayPickerInput, that will keep it opened – Menawer Aug 12 '20 at 20:37
  • Adding `hideOnDayClick` didn't change anything, as the overlay was still open before, it was just un-focusing from the input – Lara Aug 12 '20 at 20:56

1 Answers1

1

I feel a little bit silly cause as soon as I posted the question I figured out a solution. Nonetheless here it is incase anyone else has the same problem.

I had to add a forwarded ref so that in my onDayChange function I could call ref.current.focus(), and now the focus is kept. Here is the final code: (I believe the sandbox was updated to the correct solution since I was playing around in it)

function Example() {
  const [value, setValue] = React.useState(null);
  const ref = React.useRef(null);
  return (
    <div>
      <h3>DayPickerInput</h3>
      <DayPickerInput
        component={React.forwardRef((props, ref) => <CustomInput {...props} innerRef={ref}/>)}
        value={value}
        inputProps={{ ref: ref }}
        onDayChange={async day => {
           await setValue(day);
           // need to call focus here to keep focus on the input
           ref.current.focus();
        }}
      />
    </div>
  );
}

And in the custom input, the ref is no longer defined in this component, but forwarded through the props:

import React from "react";

class Input extends React.Component {
  focus() {
    this.props.innerRef.current.focus();
  }

  render() {
    return <input {...this.props} ref={this.props.innerRef} />;
  }
}

export default Input;
Lara
  • 516
  • 1
  • 3
  • 9