Home > Net >  How to render an array of component with the same props in react?
How to render an array of component with the same props in react?

Time:09-14

How can I use an array of routes for react-router-dom with components with the same props, without rendering the props to every routes seperatley?

const App = () => {
   const list = [
      {
         path: `home`,
         element: <Home />
      },
      {
         path: `section`,
         element: <Section />
      },
   ];

   return (
      <BrowserRouter>
         <Routes>
            {list.map(list => <Route element={list.element ...{ myProp={test} } } path={list.path} )}
         <Routes>
      </BrowserRouter>

   )

}

I'm sure there's a way to render these props inside my map (if I have the list in another file, for example).

Thanks!

CodePudding user response:

Try using Component instead of <Component />

const list = [
  {
    path: `home`,
    element: Home
  },
  {
    path: `section`,
    element: Section
  },
];

const App = () => {
 return (
   <BrowserRouter>
     <Routes>
       {list.map(list => <Route element={<list.element myProp={test} /> } path={list.path} )}
     <Routes>
    </BrowserRouter>
  )
}

I also moved your list out of the component for performance reasons.

CodePudding user response:

Pass a reference to the component you want to render in the element property and create a locally scoped valid React component, i.e. a Capitalized/PascalCased variable. Don't forget to use a valid React key prop on the mapped elements.

Example:

const App = () => {
  const list = [
    {
       path: 'home',
       element: Home
    },
    {
       path: 'section',
       element: Section
    },
  ];

  return (
    <BrowserRouter>
      <Routes>
        {list.map(list => {
          const Element = list.element;
          return (
            <Route
              key={list.path}
              path={list.path}
              element={<Element myProp={test} />}
            />
          );
        }}
      <Routes>
    </BrowserRouter>
  );
};

Or you could just pass the prop when declaring the list.

const App = () => {
  const list = [
    {
      path: 'home',
      element: <Home myProp={test} />
    },
    {
      path: 'section',
      element: <Section myProp={test} />
    },
  ];

  return (
    <BrowserRouter>
      <Routes>
        {list.map(list => <Route key={list.path} {...list} />)}
      <Routes>
    </BrowserRouter>
  );
};

From here though you are just one more minor tweak away from just using the useRoutes hook and pass the list routes configuration.

Example:

import { useRoutes } from 'react-router-dom';

const App = () => {
  const routes = useRoutes([
    {
      path: 'home',
      element: <Home myProp={test} />
    },
    {
      path: 'section',
      element: <Section myProp={test} />
    },
  ]);

  return routes;
};

...

<BrowserRouter>
  <App />
</BrowserRouter>
  • Related