Home > OS >  React does not render the components - I figured out the issue, but I don't know how to fix it
React does not render the components - I figured out the issue, but I don't know how to fix it

Time:06-14

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?

Thanks.

CodePudding user response:

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)}/>
  )
}

  • Related