Sai Krishnadas
Sai Krishnadas

Reputation: 3409

couldn't access history of react router

The history is undefined, while trying to call this.props.history.push("/home").

Code:

Index.js

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <HashRouter>
    <App location />
  </HashRouter>
);

App.js

export class App extends React.Component {
  handleClick = () => {
    this.props.history.push("/home");
  };
  render() {
    return (
      <div className="App">
        <button onClick={() => this.handleClick()}>Click to Nav</button>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}

React-Router: v5.2.0

CodeSandbox link: https://codesandbox.io/s/sharp-wing-ju5ou9?file=/src/App.js

Upvotes: 2

Views: 537

Answers (1)

Drew Reese
Drew Reese

Reputation: 202686

The App component needs to be either rendered by a Route component so it can be passed route props so there's a defined history prop, or decorate and export App with the withRouter Higher Order Component.

App

import React from "react";
import "./styles.css";
import { withRouter } from "react-router-dom";

class App extends React.Component {
  handleClick = () => {
    this.props.history.push("/home");
  };
  render() {
    return (
      <div className="App">
        <button onClick={() => this.handleClick()}>Click to Nav</button>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}

export default withRouter(App);

Edit couldnt-access-history-of-react-router

Alternatively you could convert App to a React function component and import and use the useHistory hook instead.

import React from "react";
import "./styles.css";
import { useHistory } from "react-router-dom";

const App = () => {
  const history = useHistory();

  const handleClick = () => {
    history.push("/home");
  };

    return (
      <div className="App">
        <button onClick={handleClick}>Click to Nav</button>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
}

export default App;

Edit couldnt-access-history-of-react-router (forked)

I see also that you are using react@18 and [email protected] and had removed the React.StrictMode component in your index.js file. There was an issue introduced by react@18 that broke RRDv5 routing (described here) that was resolved in [email protected] so I suggest you upgrade to the latest v5 version.

npm i -s react-router-dom @5

index.js

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { HashRouter } from "react-router-dom";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <HashRouter>
      <App />
    </HashRouter>
  </StrictMode>
);

Upvotes: 2

Related Questions