React-Router + React Hooks using withRouter

11,250

As per the comment by Tim Moses on the other answer, react-router now has hooks for this. Sample code has been pulled from the React Hooks docs:

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}
Share:
11,250

Related videos on Youtube

Phillip
Author by

Phillip

Software Engineer

Updated on September 15, 2022

Comments

  • Phillip
    Phillip over 1 year

    I'm starting to use React hooks in my application, but it seems like there's hurdle after hurdle to figure out. I'm not sure if it's because of the learning curve or if dependencies aren't prepared to use this new implementation. In any case..

    Before hooks, we used HOC's to connect into a specific API's whether it be Redux, React-Router, etc.. In my case, I want to get access to my React-Router properties (history, location).

    Normally it would be as simple as doing this as the bottom of the file:

    export default withRouter(SomeComponent);
    

    But now with hooks, I'm not sure how to get access to this data.

    How would I get access to this same type data from react-router with the new React hooks?

    • Apolo
      Apolo almost 5 years
      HOC should still work, you are not forced to use hooks only
    • Phillip
      Phillip almost 5 years
      Hmm I see, but is there a pure hook way to accomplish this? Are we meant to mix HOC with hooks? I was under the assumption that we should try to do everything with hooks and slowly do away with class components and HOC
    • Apolo
      Apolo almost 5 years
      hoc will provide extra props anyway. This react-router issue is what you are looking for: github.com/ReactTraining/react-router/issues/6430
  • Justin Dalrymple
    Justin Dalrymple over 2 years