ihoverlord / react-router-sample

Sample React project to define routes with JSON config and redirecting users on 404

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React Routing sample

Sample project to test defining routes with JSON and handle redirecting on 404

  1. Define routes in a JSON
const routes = {
      '/default': {
         component: Home
      },
      '/dashboard': {
         component: Dashboard
      },
      '/profile': {
         component: Profile
      }
   }
  1. Create a function to define routes dynamically
const DefineRoutes = ({ routes }) => {
   const paths = Object.keys(routes)
   let location = useLocation();
   // console.log({ location, has: routes[location.pathname] })
   if (!routes.hasOwnProperty(location.pathname)) return <Redirect to="/" />
   if (paths && paths.length > 0) {
      return (
         <>
            {paths.map(path => <Route path={path} key={path} component={routes[path].component} />)}
         </>
      )
   }

}

This function handles 404 and redirects the user to /

  1. Define router and import the routes
<Router>
 <Switch>
  <Route exact path="/" component={Home} />
  <DefineRoutes routes={routes} />
 </Switch>
</Router>

About

Sample React project to define routes with JSON config and redirecting users on 404


Languages

Language:JavaScript 59.3%Language:HTML 26.4%Language:CSS 14.3%