UNPKG

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