Created
February 22, 2021 21:25
-
-
Save dev-cyprium/9e2ebfea5ee2f268919bca33148eec39 to your computer and use it in GitHub Desktop.
router/index.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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