I am facing an error of “TypeError: Cannot read properties of undefined (reading ‘push’)”

I have been facing this issue while using history.push(‘/pathname’) in app.js component. my requirement is that I have to use this history.push inside an onclick handler defined in app.js component which is then sent to button component in via props. I am not able to figure out the solution of this error. (The button component is AppointmentNextBtn). Please guide me.

import { useHistory } from "react-router-dom";
function App(){
  const history = useHistory();
  const onClickNextDateHandler = () => {
history.push("/selectlocation/appointment/selectdate");
console.log("date button runs");
setNextBtnState("time");

};

return(
<Route exact path="/selectlocation/appointment">
        <Toappointmentcontainer
          postAppointmentRequest={postRequestAppointment}
        />
        <div className="btnwidget">
          <AppointmentNextBtn
            onClickDateHandler={onClickNextDateHandler}
            displayState={nextBtnState}
            text="Next"
            button="button"
          />
        </div>
      </Route>

)

}

Answer

You cannot use history in the same file you declare your route. History objects will always be unavailable in this case. Best way is to do directly it in appointmentNextBtn.