Search code examples
javascriptreactjsreact-component

Rendering React Components from an Object


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.


Solution

  • 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