middleStackoverflower
middleStackoverflower

Reputation: 262

How to map Routes from array?

I Have some routes:

export const publicRoutes = [
    {
        path: MAIN_ROUTE,
        Component: Main
    },
    {
        path: ABOUT_ROUTE,
        Component: About
    }
]

And I want to create some Routes into BrowserRouter:

<BrowserRouter>
  <Routes>
    {publicRoutes.map(({path, Component}) => (
        <Route key={path} path={path} element={Component}/> // Type '() => JSX.Element' is not assignable to type 'ReactNode'. 
    ))}
  </Routes>
</BrowserRouter>

TypeScript throws an error Type '() => JSX.Element' is not assignable to type 'ReactNode'.

Upvotes: 0

Views: 1577

Answers (1)

Louay Al-osh
Louay Al-osh

Reputation: 3405

You have to define the routes array items as jsx intially

export const publicRoutes = [
    {
        path: MAIN_ROUTE,
        Component: <Main/>
    },
    {
        path: ABOUT_ROUTE,
        Component: <About/>
    }
]

You can also use useRoutes to make things even more elegant (https://reactrouter.com/docs/en/v6/hooks/use-routes#useroutes)

Example from Docs:

import * as React from "react";
import { useRoutes } from "react-router-dom";

function App() {
  let element = useRoutes([
    {
      path: "/",
      element: <Dashboard />,
      children: [
        {
          path: "messages",
          element: <DashboardMessages />,
        },
        { path: "tasks", element: <DashboardTasks /> },
      ],
    },
    { path: "team", element: <AboutPage /> },
  ]);

  return element;
}

Upvotes: 3

Related Questions