Skip to content

Instantly share code, notes, and snippets.

@dev-cyprium
Created February 22, 2021 21:25
Show Gist options
  • Select an option

  • Save dev-cyprium/9e2ebfea5ee2f268919bca33148eec39 to your computer and use it in GitHub Desktop.

Select an option

Save dev-cyprium/9e2ebfea5ee2f268919bca33148eec39 to your computer and use it in GitHub Desktop.
router/index.js
import React, {
useContext,
createContext,
useEffect,
useState,
cloneElement
} from "react";
const RouterContext = createContext({ route: "", push: () => {} });
const RouterView = ({ config }) => {
const router = useRouter();
let Component = config[router.route] || null;
return <Component />;
};
const useRouter = () => {
const ctx = useContext(RouterContext);
return ctx;
};
const AppRouter = ({ children }) => {
const [route, setRoute] = useState("/");
function push(newRoute) {
setRoute(newRoute);
}
useEffect(() => {
window.history.pushState({}, "", route);
}, [route]);
return (
<RouterContext.Provider value={{ route, push }}>
{children}
</RouterContext.Provider>
);
};
export { RouterView, AppRouter, useRouter, Link };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment