Suppose I have the following object that takes components as entries:
import Comp1 from './Comp1'
import Comp2 from './Comp2'
import Comp3 from './Comp3'
const components = { 'comp1' : Comp1, 'comp2' : Comp2, 'comp3' : Comp3 }
I would like to use this object to render these components:
Object.keys(components).map((key, i) => (
    <div key={i}> 
        <components[key] /> // this does not work
    </div>
))}
In reality I am trying to render routes using a config object:
export const routes =   {
'home' : {  
    path: '/', 
    component: Home,
    exact: true,
    access: {
        anonymous: true
    },
    navigation: {
        label: 'Home',
        icon: 'fa-home',
        show: true
    }
},
....
const Routes = () => (
    <div>
        {Object.keys(routes).map((k, i) => (
            <Route 
                key={i} 
                exact={routes[k].exact} 
                path={routes[k].path} 
                render={() => 
                    !routes[k].access.anonymous ? ( 
                        <Redirect to="/login"/>  
                    ) : ( 
                        <routes[k] /> // nope
                    )
                } 
            />
        ))}
    </div>
)
I was thinking that <components[key] /> is JSX and  React does not require the use of JSX, so perhaps the solution is to render these components without JSX, using standard JS. Though I not sure how to do that. 
routes[k] is not a React component, routes[k].component is. Also, since you are only interested in the values use Object.values instead of Object.keys.
Object.values(routes).map((route, i) => (
    <Route key={i} 
           exact={route.exact} 
           path={route.path} 
           render={() => 
              !route.access.anonymous ? ( 
                  <Redirect to="/login"/>  
              ) : ( 
                  <route.component /> 
              )
          } 
      />
  ))
Working example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With