hooks.js 1.3 KB

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