Skip to content
Advertisement

Is this a good practice? [closed]

I`m doing a project with react and I decided to make routes functionality a little different, I put the routes details to an separated file as an array: routes details file, and on the routes component I iterate through the array using the map function: routes component. But I don’t know if what I did is something recommended, do you think it’s better to put the routes in a static way directly in the component or is there a better solution?

Advertisement

Answer

It is better to use the useRoutes function provided by the react-router-dom package.

This makes your code shorter and authentication can be added easily using this procedure.

This way, you can define the main routes as an object like:

routes = (loggedIn) => [
    {
        path: '/',
        children: [
            // unprotected routes here
        ]
    },
    {
        path: '/main',
        element: loggedIn ? <Layout /> : <Navigate to='/login' />
        children: [
            // protected routes here
        ]
    }
]

Then return useRoutes in the route component like:

const { loggedIn } = useSelector((state) => state.auth);
return useRoutes(routes(loggedIn), '');

useRoutes API: https://reactrouter.com/docs/en/v6/api#useroutes

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement