i'd like to achieve open react-datepicker calendar on button click outside of this component with ref. It is working fine if its outside of conditional rendering. If i put into a condition statementm i'll get TypeError: this.calendarRef.current is null. It is class component and calendarRef is defined in constructor.
import React from 'react';
import Grid from '@material-ui/core/Grid';
import Button from '@material-ui/core/Button';
import DatePicker from "react-datepicker";
const MyCustomDatePicker = React.forwardRef((props, ref) => (
<DatePicker
ref={ref}
selected={new Date()}
popperPlacement="bottom-start"
monthsShown={2}
/>
));
class DateRangeCustom extends React.Component {
constructor(props) {
super(props);
this.state = {
currentDate: '01/12/2021',
ddCalendarOn: false,
endDate: '08/12/2021',
};
this.calendarRef = React.createRef();
}
handleCalendarBtnClick = () => {
console.log('*** HANDLE CALENDAR BTN ***');
this.setState((state) => ({
ddCalendarOn: !state.ddCalendarOn
}));
this.calendarRef.current.setOpen(true);
}
render() {
console.log('*** render ****')
return (
<Grid container>
<Grid>
<Grid container direction="column">
<Button
onClick={this.handleCalendarBtnClick}
>
SHOW
</Button>
{this.state.ddCalendarOn && <MyCustomDatePicker
ref={this.calendarRef}
/>}
</Grid>
</Grid>
</Grid>
);
}
}
export default DateRangeCustom;
Thank you for any advice.
MyCustomDatePickerinside another component? Where is ay conditional rendering occurring that you are referring to? Can you include a full component example so we may see everything that touches thatcalendarRef?