https://github.com/ashok-khanna/react-snippets/blob/main/Router.js Skip to content Sign up * Product + Features + Mobile + Actions + Codespaces + Packages + Security + Code review + Issues + Integrations + GitHub Sponsors + Customer stories * Team * Enterprise * Explore + Explore GitHub + Learn and contribute + Topics + Collections + Trending + Learning Lab + Open source guides + Connect with others + The ReadME Project + Events + Community forum + GitHub Education + GitHub Stars program * Marketplace * Pricing + Plans + Compare plans + Contact Sales + Education [ ] * # In this repository All GitHub | Jump to | * No suggested jump to results * # In this repository All GitHub | Jump to | * # In this user All GitHub | Jump to | * # In this repository All GitHub | Jump to | Sign in Sign up {{ message }} ashok-khanna / react-snippets Public * Notifications * Fork 1 * Star 59 * Code * Issues 0 * Pull requests 0 * Actions * Projects 0 * Wiki * Security * Insights More * Code * Issues * Pull requests * Actions * Projects * Wiki * Security * Insights Permalink main Switch branches/tags [ ] Branches Tags Could not load branches Nothing to show {{ refName }} default View all branches Could not load tags Nothing to show {{ refName }} default View all tags react-snippets/Router.js / Jump to Code definitions [ ] Router Function onLocationChange Function navigate Function Link Function onClick Function Code navigation index up-to-date Go to file * Go to file T * Go to line L * Go to definition R * * Copy path * Copy permalink This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. @ashok-khanna ashok-khanna Routing in React (without React-Router) Latest commit ab53ff3 May 13, 2022 History 1 contributor Users who have contributed to this file 120 lines (84 sloc) 3.22 KB Raw Blame * Open with Desktop * View raw * * View blame This file contains 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 Show hidden characters /* Implements React Routing in Plain React, without reliance on React-Router or any other libraries. To use: In your top-level React Component (e.g. App or Index.js): - Import Router (e.g.: import Router from './Router') - Create a const with your routes and their associated component - Create a const with the component to show on urls not routed (i.e. 404 page) - Return a Router component as the top-level component of your App Example: ```function App() { ... const routes = [{path:"/", component:}, {path:"/login", component:}] ... const defaultComponent = return ( ) } ``` Then to use routes: - If you want to mimic the experience, use , e.g.: Text or React Component - If you want to add an onClick event handler to buttons etc. use the `navigate` function, e.g.: - You need to import Link & Navigate to use them, e.g.: import { Navigate, Link } from "./Components/AKRouter"; And that's it! */ /* Code Starts Here */ import React from 'react'; import { useEffect, useState } from 'react'; export default function Router ({routes, defaultComponent}) { // state to track URL and force component to re-render on change const [currentPath, setCurrentPath] = useState(window.location. pathname); useEffect(() => { // define callback as separate function so it can be removed later with cleanup function const onLocationChange = () => { // update path state to current window URL setCurrentPath(window.location.pathname); } // listen for popstate event window.addEventListener('popstate', onLocationChange); // clean up event listener return () => { window.removeEventListener('popstate', onLocationChange) }; }, []) console.log(Array.isArray(routes)) console.log(typeof routes) return routes.find(({path, component}) => path === currentPath)?. component || defaultComponent } /* Use the below in buttons and programmatically to navigate to pages */ export function navigate (href) { // update url window.history.pushState({}, "", href); // communicate to Routes that URL has changed const navEvent = new PopStateEvent('popstate'); window.dispatchEvent(navEvent); } /* Use the below when you want the full hyperlink behaviour */ export function Link ({ className, href, children }) { const onClick = (event) => { // if ctrl or meta key are held on click, allow default behavior of opening link in new tab if (event.metaKey || event.ctrlKey) { return; } // prevent full page reload event.preventDefault(); // update url window.history.pushState({}, "", href); // communicate to Routes that URL has changed const navEvent = new PopStateEvent('popstate'); window.dispatchEvent(navEvent); }; return ( {children} ); }; * Copy lines * Copy permalink * View git blame * Reference in new issue [ ] Go * (c) 2022 GitHub, Inc. * Terms * Privacy * Security * Status * Docs * Contact GitHub * Pricing * API * Training * Blog * About You can't perform that action at this time. You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.