React-Router + React Hooks using withRouter
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>
);
}
Related videos on Youtube
Comments
-
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 almost 5 yearsHOC should still work, you are not forced to use hooks only
-
Phillip almost 5 yearsHmm 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 almost 5 yearshoc will provide extra props anyway. This react-router issue is what you are looking for: github.com/ReactTraining/react-router/issues/6430
-
-
Justin Dalrymple over 2 yearsUpdated link url: v5.reactrouter.com/web/api/Hooks