hooks.js 1.1 KB

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