简体   繁体   中英

How to dynamically render Route components in React-router-dom and React

So, I want to create routes this way:

<Routes>
  {
    SidebarItems.map(el => 
      <Route key={el.text} path={el.link} element={<el.text/>}/>
    )
  }
</Routes>

SidebarItems

export const SidebarItems: Array<SidebarItem> = [
    {
        text: "Educatie",
        icon: SchoolIcon,
        link: '/educatie'
    },
    {
        text: "Experienta",
        icon: DoneIcon,
        link: '/experienta'
    },
    {
        text: "Judete",
        icon: MapIcon,
        link: '/judete'
    },
    {
        text: "Localitati",
        icon: MapsHomeWorkIcon,
        link: '/localitati'
    },
    {
        text: "Tipuri de contract",
        icon: ArticleIcon,
        link: '/tipuricontract'
    }
];

The components have the name from the text property. I observed that if I explicitly call a component, like:

<Route path="/" element={<Educatie/>}/>

it will work. But only using a text doesn't work - I need to reference the component itself.

How can I do that in my specific case?

I would do something like this :

 const Component1 = React.lazy(() => import ('./Component1')); const Component2 = React.lazy(() => import ('./Component2')); const componentHandler = (text) => { switch text { case 'component 1': return <Component1 / > ; case 'component 2': return <Component2 / > default: null } } ////////// { SidebarItems.map(el => <Route key = {el.text} path = {el.link} element={componentHandler(el.text)}/> ) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM