1import { useHistory } from "react-router-dom";
2
3function HomeButton() {
4 let history = useHistory();
5
6 function handleClick() {
7 history.push("/home");
8 }
9
10 return (
11 <Button type="button" onClick={handleClick}>
12 Go home
13 </Button>
14 );
15}
1import { useLocation } from 'react-router-dom'
2
3// Location is, for example: http://localhost:3000/users/new
4
5// Care! MyComponent must be inside Router to work
6const MyComponent = () => {
7 const location = useLocation()
8
9 // location.pathname is '/users/new'
10 return <span>Path is: {location.pathname}</span>
11}
12
13export default MyComponent
1import { useMemo } from "react";
2import {
3 useParams,
4 useLocation,
5 useHistory,
6 useRouteMatch,
7} from "react-router-dom";
8import queryString from "query-string";
9
10// Usage
11function MyComponent() {
12 // Get the router object
13 const router = useRouter();
14
15 // Get value from query string (?postId=123) or route param (/:postId)
16 console.log(router.query.postId);
17
18 // Get current pathname
19 console.log(router.pathname);
20
21 // Navigate with with router.push()
22 return <button onClick={(e) => router.push("/about")}>About</button>;
23}
24
25// Hook
26export function useRouter() {
27 const params = useParams();
28 const location = useLocation();
29 const history = useHistory();
30 const match = useRouteMatch();
31
32 // Return our custom router object
33 // Memoize so that a new object is only returned if something changes
34 return useMemo(() => {
35 return {
36 // For convenience add push(), replace(), pathname at top level
37 push: history.push,
38 replace: history.replace,
39 pathname: location.pathname,
40 // Merge params and parsed query string into single "query" object
41 // so that they can be used interchangeably.
42 // Example: /:topic?sort=popular -> { topic: "react", sort: "popular" }
43 query: {
44 ...queryString.parse(location.search), // Convert string to object
45 ...params,
46 },
47 // Include match, location, history objects so we have
48 // access to extra React Router functionality if needed.
49 match,
50 location,
51 history,
52 };
53 }, [params, match, location, history]);
54}
1import { useRouteMatch } from "react-router-dom";
2
3function BlogPost() {
4 let match = useRouteMatch("/blog/:slug");
5
6 // Do whatever you want with the match...
7 return <div />;
8}
9