React-datepicker: How can I set focus on the input element from the outside?

Created on 21 Dec 2015  路  7Comments  路  Source: Hacker0x01/react-datepicker

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?

Hacktoberfest enhancement help wanted

Most helpful comment

There is yet a more elegant way using a ref:

   <DatePicker ... ref={(datepicker) => { this.datepicker = datepicker }} />

and then just:

    focusHiddenDatepicker () {
        this.datepicker.input.focus();
    }

All 7 comments

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>
                &nbsp;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();
    }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

evolve2k picture evolve2k  路  3Comments

lclemence picture lclemence  路  3Comments

jbccollins picture jbccollins  路  3Comments

jcabrerazuniga picture jcabrerazuniga  路  3Comments

tamitutor picture tamitutor  路  3Comments