routes react hooks code example
Example 1: react router hooks
import { useRouteMatch } from "react-router-dom";
function BlogPost() {
let match = useRouteMatch("/blog/:slug");
return <div />;
}
Example 2: react router hooks
import { useMemo } from "react";
import {
useParams,
useLocation,
useHistory,
useRouteMatch,
} from "react-router-dom";
import queryString from "query-string";
function MyComponent() {
const router = useRouter();
console.log(router.query.postId);
console.log(router.pathname);
return <button onClick={(e) => router.push("/about")}>About</button>;
}
export function useRouter() {
const params = useParams();
const location = useLocation();
const history = useHistory();
const match = useRouteMatch();
return useMemo(() => {
return {
push: history.push,
replace: history.replace,
pathname: location.pathname,
query: {
...queryString.parse(location.search),
...params,
},
match,
location,
history,
};
}, [params, match, location, history]);
}