1

I like to use useRoutes() hook from
https://github.com/Paratron/hookrouter
but I have too many pages, and get lot of repeating code,
I try generate some areas, please help me write genRoutes() function

Example code:

const pages = [{ name: 'aaa' }, { name: 'bbb' }, { name:'ccc' }]
const routes = genRoutes(pages)
console.log(routes)

> {
>   '/aaa': () => <AaaPage />,
>   '/bbb': () => <BbbPage />,
>   '/ccc': () => <CccPage />
> }
Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
Eugene Balashov
  • 105
  • 1
  • 13

1 Answers1

1

The library you're using doesn't provide value except for using the routes as hook. A hook shouldn't really be used for such cases. The following approach doesn't need a library (except react itself of course) and has a nice declarative syntax.

import { Route, Switch } from 'react-router-dom';
...

const routes = [
    {
        path: '/',
        component: HomeComponent
    },
    {
        path: '/b',
        component: ComponentB
    },
    {
        path: '/c',
        component: ComponentC
    }
];

return (
    <Switch>
        {routes.map(({ path, component }) => (
            <Route path={path} component={component} exact />
        ))}
    </Switch>
);

This config style approach could be extended with further options (exact for example).

sandrooco
  • 8,016
  • 9
  • 48
  • 86