Search code examples
reactjscreate-ref

react-day-picker ref current scrollIntoView not accessible


I am using react-day-picker. I want to scroll into "calendar" - DayPicker Component after i click into input (problem is when page is scrolled, then calendar is not in viewport. I tried this approach (simplified):

import React from 'react';
import DayPickerInput from 'react-day-picker/DayPickerInput';

class DatePicker extends React.Component {
    constructor(props) {
        super(props);
        this.fromDayPickerRef = React.createRef();
        this.toDayPickerRef = React.createRef();

        this.handleOnDayPickerShow = ref => { this[ref].current.scrollIntoView() }
    }
    render() {
        const {from, to} = this.state;
        const modifiers = {start: from, end: to};
        return (
            <div className="InputFromTo">
                <DayPickerInput
                    ...
                    dayPickerProps={{
                        ...
                        ref: this.fromDayPickerRef,
                    }}
                    ...
                    onDayPickerShow={() => this.handleOnDayPickerShow("fromDayPickerRef")}
                /><br/>
                <span className="InputFromTo-to">
                    <DayPickerInput
                        ...
                        dayPickerProps={{
                            ...
                            ref: this.toDayPickerRef,
                        }}
                        ...
                        onDayPickerShow={() => this.handleOnDayPickerShow("toDayPickerRef")}
                    />
                </span>
            </div>
    }
}

I am able to access .current but without HTML DOM props (e.g. offSetTop) or functions. Any guess?


Solution

  • I figured it out. You can't just reference function component like this (possible using forwardRef). But reference is passed later to DOM element. You need to do it in following way:

    dayPickerProps={{
        ...
        ref: el => {this.fromDayPickerRef = el},
    }}