Home > Mobile >  Is it possible to use Template literal for Component name in React?
Is it possible to use Template literal for Component name in React?

Time:12-18

it may be weird, but I want to dynamically route in ReactJs. So, I tried using Template literal for generating the Component name, but its not working. Any idea how its done? or is it not allowed?

<Routes>
{
    Object.keys(Nav_items).map((key,index)=>{
    <Route path={`/${pageNav[key]}`} exact element={<`$(pageNav[key])`/>} ></Route>)
}
<Route path={'/home'}  exact element={<HomePage/>} ></Route>
</Routes>

CodePudding user response:

For this you must compute the component before rendering the JSX.

Choosing the Type at runtime

<Routes>
  {Object.keys(Nav_items).map((key) => {
    const Component = pageNav[key];
    return <Route path={`/${Component}`} element={<Component />} />
  )}
  <Route path={'/home'} element={<HomePage/>} />
</Routes>

This seems to assume that the route path and component to be rendered are named the same, which may not always be ideal or practical.

I suggest some structure more like:

const Nav_items = [
  {
    path: ".....",
    Component: MyComponent,
  },
  ...
];

Explicitly specify a path and component for each entry:

<Routes>
  {Nav_items.map(({ path, Component }) => (
    <Route key={path} path={path} element={<Component />} />
  ))}
  <Route path={'/home'} element={<HomePage/>} />
</Routes>

CodePudding user response:

You can not use template literal string for components.

But you can use this approach for your purpose

<Routes>
{
  Object.keys(Nav_items).map((key,index) => {
    const Component = pageNav[key];
    return (
      <Route path={`/${pageNav[key]}`} exact element={<Component />} />
    )
  })
  <Route path={'/home'}  exact element={<HomePage/>} ></Route>
</Routes>
  • Related