UNPKG

1.18 kBJavaScriptView Raw
1import React from "react";
2import invariant from "tiny-invariant";
3
4import Context from "./RouterContext.js";
5import matchPath from "./matchPath.js";
6
7const useContext = React.useContext;
8
9export function useHistory() {
10 if (__DEV__) {
11 invariant(
12 typeof useContext === "function",
13 "You must use React >= 16.8 in order to use useHistory()"
14 );
15 }
16
17 return useContext(Context).history;
18}
19
20export function useLocation() {
21 if (__DEV__) {
22 invariant(
23 typeof useContext === "function",
24 "You must use React >= 16.8 in order to use useLocation()"
25 );
26 }
27
28 return useContext(Context).location;
29}
30
31export function useParams() {
32 if (__DEV__) {
33 invariant(
34 typeof useContext === "function",
35 "You must use React >= 16.8 in order to use useParams()"
36 );
37 }
38
39 const match = useContext(Context).match;
40 return match ? match.params : {};
41}
42
43export function useRouteMatch(path) {
44 if (__DEV__) {
45 invariant(
46 typeof useContext === "function",
47 "You must use React >= 16.8 in order to use useRouteMatch()"
48 );
49 }
50
51 return path
52 ? matchPath(useLocation().pathname, path)
53 : useContext(Context).match;
54}