1

i am trying to use useRef in my react functional component, but when i try to access it I am getting error "TypeError: Cannot read property 'onMonthSelect' of undefined while using "useRef" " .

Here is the code below for this

import React, { useRef, useState, useEffect } from "react";
import moment from "moment";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
import { SingleDatePicker } from "react-dates";

const SingleDatePickerComponent = () => {
  const monthController = useRef();
  const [createdAt, setCreatedAt] = useState(moment());

  const onDateChange = (createdAt) => {
    console.log(createdAt);
    setCreatedAt(createdAt);
  };

  useEffect(() => {
    console.log(monthController);
    // TODO: check if month is visible before moving
    monthController.current.onMonthSelect(
      monthController.current.month,
      createdAt.format("M")
    );
//In this useEffect i am getting the error
  }, [createdAt]);

  return (
    <div>
      <div style={{ marginLeft: "200px" }}>
      </div>
      <SingleDatePicker
        date={createdAt}
        startDateId="MyDatePicker"
        onDateChange={onDateChange}
        renderMonthElement={(...args) => {
          // console.log(args)
          monthController.current = {
            month: args[0].month,
            onMonthSelect: args[0].onMonthSelect,
          };
          // console.log(monthController)
          return args[0].month.format("MMMM");
        }}
        id="SDP"
      />
    </div>
  );
};

export default SingleDatePickerComponent;
Ratnabh Kumar Rai
  • 554
  • 2
  • 7
  • 24

1 Answers1

1

The ref value won't be set yet on the initial render. Use a guard clause or Optional Chaining operator on the access.

useEffect(() => {
  // TODO: check if month is visible before moving
  monthController.current && monthController.current.onMonthSelect(
    monthController.current.month,
    createdAt.format("M")
  );
}, [createdAt]);

or

useEffect(() => {
  // TODO: check if month is visible before moving
  monthController.current?.onMonthSelect(
    monthController.current.month,
    createdAt.format("M")
  );
}, [createdAt]);

It may also help to provide a defined initial ref value.

const monthController = useRef({
  onMonthSelect: () => {},
});
Drew Reese
  • 165,259
  • 14
  • 153
  • 181