How can I set focus on the input element from the outside?
I'd like to autofocus the input element and show the calendar once the DatePicker is rendered, in order to allow the user to select a date w/o forcing him to click on the input field first. Is there a way?
I don't think that's possible right now. You could trigger a click with jQuery on page load, but that's a bit fragile. If you can work out something else, I'm happy to review it.
Having a prop to autoFocus doesn't sound like a bad idea.
I'd be a fan of this feature as well. I'm running into an issue where i need to manually control the focus and blur
Is there someone working on this autofocus feature right now?
If no, maybe i can help tonight , i need this feature so badly as well so :D
@jxm262 why not just use vanilla js to focus/blur the input element?
export default class Datejumper extends Component {
toggleDate = this.props.toggleDate;
shownDate = this.props.shownDate;
focusHiddenDatepicker () {
document.getElementById('date-jumper').focus();
}
render () {
return (
<div className="btn btn-default date-jump"
onClick={this.focusHiddenDatepicker.bind(this)}>
<i className="fa fa-clock-o"></i>
Jump To Date
<DatePicker selected={moment(this.shownDate)}
onChange={this.toggleDate}
id="date-jumper" />
</div>
);
}
}
Thanks @zelias500 , your "focusHiddenDatepicker" method saved me day. The calendar is now opening happily on button click.
There is yet a more elegant way using a ref:
<DatePicker ... ref={(datepicker) => { this.datepicker = datepicker }} />
and then just:
focusHiddenDatepicker () {
this.datepicker.input.focus();
}
one step further from @adamlibusa, using the public API of the component:
Seems the picker has some public methods, so you may not need to access any input element directly:
export class ReactDatePicker<
CustomModifierNames extends string = never,
WithRange extends boolean | undefined = undefined,
> extends React.Component<ReactDatePickerProps<CustomModifierNames, WithRange>> {
readonly setBlur: () => void;
readonly setFocus: () => void;
readonly setOpen: (open: boolean, skipSetBlur?: boolean) => void;
readonly isCalendarOpen: () => boolean;
}
So, same as before, save the component reference:
<DatePicker ... ref={(datepicker) => { this.datepicker = datepicker }} />
Focus using the API:
focusHiddenDatepicker () {
this.datepicker.setFocus();
}
Perhaps you may want only to open the calendar without focus also:
focusHiddenDatepicker () {
this.datepicker.setOpen(true, false)
}