Answers for "react router hook"

1

react useLocation()

import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  useLocation
} from "react-router-dom";

function usePageViews() {
  let location = useLocation();
  React.useEffect(() => {
    ga.send(["pageview", location.pathname]);
  }, [location]);
}

function App() {
  usePageViews();
  return <Switch>...</Switch>;
}

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  node
);
Posted by: Guest on December-10-2020
3

react router dom current path hook

import { useLocation } from 'react-router-dom'

// Location is, for example: http://localhost:3000/users/new

// Care! MyComponent must be inside Router to work
const MyComponent = () => {
	const location = useLocation()
    
    // location.pathname is '/users/new'
    return <span>Path is: {location.pathname}</span>
}

export default MyComponent
Posted by: Guest on June-12-2020
0

react router hooks

import { useMemo } from "react";
import {
  useParams,
  useLocation,
  useHistory,
  useRouteMatch,
} from "react-router-dom";
import queryString from "query-string";

// Usage
function MyComponent() {
  // Get the router object
  const router = useRouter();

  // Get value from query string (?postId=123) or route param (/:postId)
  console.log(router.query.postId);

  // Get current pathname
  console.log(router.pathname);

  // Navigate with with router.push()
  return <button onClick={(e) => router.push("/about")}>About</button>;
}

// Hook
export function useRouter() {
  const params = useParams();
  const location = useLocation();
  const history = useHistory();
  const match = useRouteMatch();

  // Return our custom router object
  // Memoize so that a new object is only returned if something changes
  return useMemo(() => {
    return {
      // For convenience add push(), replace(), pathname at top level
      push: history.push,
      replace: history.replace,
      pathname: location.pathname,
      // Merge params and parsed query string into single "query" object
      // so that they can be used interchangeably.
      // Example: /:topic?sort=popular -> { topic: "react", sort: "popular" }
      query: {
        ...queryString.parse(location.search), // Convert string to object
        ...params,
      },
      // Include match, location, history objects so we have
      // access to extra React Router functionality if needed.
      match,
      location,
      history,
    };
  }, [params, match, location, history]);
}
Posted by: Guest on May-31-2021

Code answers related to "react router hook"

Code answers related to "Javascript"

Browse Popular Code Answers by Language