iterating on react components

Viewed 44

i wanted to iterate on the list of components as you can there is lot of redundancy so for example i have long list of routes just as given below

          <Route
            exact
            path={Routes.HOME}
            render={() => (
              <LandingPage
                setValue={setValue}
                setSelectedIndex={setSelectedIndex}
              />
            )}
          />
          <Route
            exact
            path={Routes.SERVICES}
            render={() => (
              <ServicesPage
                setValue={setValue}
                setSelectedIndex={setSelectedIndex}
              />
            )}
          />
          <Route
            exact
            path={Routes.MOBILE_APPS}
            render={() => (
              <MobileAppsPage
                setValue={setValue}
                setSelectedIndex={setSelectedIndex}
              />
            )}
          />

i would create a list like below

const list = [
{path: Routes.HOME, component: LandingPage},
{path: Routes.SERVICES, component: ServicesPage},
{path: Routes.MOBILE_APPS, component: MobileAppsPage}];

and i want to achieve below

list.map((obj) => (
          <Route
            exact
            path={obj.path}
            render={() => (
              <obj.component
                setValue={setValue}
                setSelectedIndex={setSelectedIndex}
              />
            )}
          />
))
1 Answers

When rendering a custom component, you must have its name Capitalized:

// Good
<Component/>
<Obj.Component/>
<Obj.component/>

// Bad
<component/>
<obj.component/>
<obj.Component/>
list.map(({ path, component: Component }) => (
  <Route
    exact
    path={path}
    render={() => (
      <Component setValue={setValue} setSelectedIndex={setSelectedIndex} />
    )}
  />
));

// Same
list.map((obj) => {
  const { component: Component, path } = obj;
  return <Route path={path} render={() => <Component {...}/>} />;
});

Related