1

I am new to ReactJS and would like to implement some level of modularity within my code to be able to easily add/implement new (nested) routes from a single file/JSON array.

I already tried to instantiate a JSON Array object containing the mandatory parameters expected by the <Route> component, then importing this exported variable into App.js to iterate through it in order to dynamically generate the routes - with very few lines of code - but I am encountering many issues, namely, with the nested route and the default catch-all behaviour.

import React, { lazy } from 'react'
import { Redirect } from 'react-router-dom'

const routes = [
    {
        path: '/about',
        component: lazy(() => import(`./about`))
    },
    --- SNIP ---
    {
        path: '/resources',
        component: lazy(() => import(`./resources`)),
        routes: [
            {
                path: '/resources/all-resources',
                component: lazy(() => import(`./resources/all-resources`))
            },
            {
                path: '/resources/blog',
                exact: true,
                component: lazy(() => import(`./resources/blog`))
            },
            {
                component: () => <Redirect to="/404" />
            }
        ],
    },
    --- SNIP ---
    {
        component: lazy(() => import(`./not-found`))
    }
]

export default routes;
import React, { Suspense } from 'react';
import { BrowserRouter, Redirect, Route, Switch } from 'react-router-dom';
import { createGlobalStyle, ThemeProvider } from 'styled-components';

import routes from './routes';

--- SNIP ---

function App() {
  return (
    <ThemeProvider theme={{ mode: 'dark' }}>
      <>
        <GlobalStyle />
        <BrowserRouter>
          <Switch>
            <Suspense fallback={<div>Loading...</div>}>
              {
                routes.map((route) =>
                  <Route path={route.path} component={route.component} exact={route.exact} />
                )
              }
            </Suspense>
          </Switch>
        </BrowserRouter>
      </>
    </ThemeProvider>
  );
}

export default App;

See the following screenshots showing the /404 component being displayed despite being in a valid and pre-defined endpoint:

enter image description here

See the nested route not working properly - should be displayed All Resources instead of Resources:

enter image description here

I expect all the routes to be read from the const routes exported object and routed properly - including the nested and /404 catch-all page.

aress31
  • 340
  • 5
  • 20

0 Answers0