How can I have dynamic input inside the react router element?

Viewed 28

I just encountered a problem with the react-router element:

import Home from '../../views/newssandbox/home/Home'
import RightList from '../../views/newssandbox/right-manage/RightList'
import RoleList from '../../views/newssandbox/right-manage/RoleList'
.....

const LocalRouterMap = {
  "/home": Home,
  "/user-manage/list": UserList,
  "/right-manage/role/list": RoleList,
  "/right-manage/right/list": RightList,
  ...
}

I want my code to work as this

<Route path='/home' element={<Home />} />
<Route path='/user-manage/list' element={<UserList />} />
<Route path='/right-manage/role/list' element={<RoleList />} />

How should I change this one?

backRouterList.map(item => {
  {/* console.log(item.key) */}
  <Route path={item.key} key={item.key} element={LocalRouterMap[item.key]} />
})
1 Answers

Given an array of route path-component pairs:

const LocalRouterMap = {
  "/home": Home,
  "/user-manage/list": UserList,
  "/right-manage/role/list": RoleList,
  "/right-manage/right/list": RightList,
  ...
}

When mapping the array you will need to first create a valid local React component variable and render it out on the Route component's element prop as JSX.

Example:

backRouterList.map(item => {
  const Component = LocalRouterMap[item.key];
  return (
    <Route path={item.key} key={item.key} element={<Component />} />
  );
})

Edit how-can-i-have-dynamic-input-inside-the-react-router-element

You could optimize this a bit by moving the JSX part to the LocalRouterMap object.

const LocalRouterMap = {
  "/home": <Home />,
  "/user-manage/list": <UserList />,
  "/right-manage/role/list": <RoleList />,
  "/right-manage/right/list": <RightList />,
  ...
}

Then you can just pass the element.

backRouterList.map(item => (
  <Route
    path={item.key}
    key={item.key}
    element={LocalRouterMap[item.key]}
  />
))
Related