1

I have an array of components

[
  {
    componentName: 'FieldHeader',
    props: {title:'bla bla},
    showOnDate: '01/01/2019'
  },
  {
    componentName: 'RadioButton',
    props: {},
    showOnDate: '01/01/2018'
  }
]

And I am trying to dynamically create elements from this array.

I have an array that has all the components in it.

I am figuring something like:

for (var i=0; i < objects.length; i++) {
        <components[objects[i].componentName] {...props}>
}

but doing something like:

<components['FieldHeader'] {...props}> 

throws a compile error.

Is there a way to dynamically render react elements like this?

Abhishek Kumawat
  • 780
  • 1
  • 10
  • 25
RobKohr
  • 6,611
  • 7
  • 48
  • 69
  • how does the `components` object look like? is it just a map of component names or components ? – Dhiraj Oct 17 '18 at 20:31
  • @Dhiraj I'm guessing it looks like what's shown under the text "I have an array of components". Which is inaccurate, but I think we know what he means. – Dave Newton Oct 17 '18 at 20:48
  • @DaveNewton completely understand. I figured its just better to proceed once all the inaccurate statements are fully answered. Better use of everybody's time I believe. – Dhiraj Oct 17 '18 at 21:45
  • @Dhiraj It's perfectly clear what the OP meant. – Dave Newton Oct 17 '18 at 22:12
  • Is this not a duplicate of https://stackoverflow.com/questions/33471880/dynamic-tag-name-in-jsx-and-react? – asgerhallas Oct 18 '18 at 05:40

2 Answers2

0

You cannot instantiate components using the string class name.

Instead try this:

const components = [
  {
    component: <FieldHeader {...props} >,
    props: {title:'bla bla},
    showOnDate: '01/01/2019'
  },
  {
    component: <RadioButton {...props} >,
    props: {},
    showOnDate: '01/01/2018'
  }
];

return components.map((c) => c.component);
Paras
  • 9,258
  • 31
  • 55
0

If you mean array of components, check this out:

Try using .map() or .forEach(). And don't forget to return your component.

Import your components, example: import FieldHeader from './components'

Now define an array, and check that componentName is not a string, but the imported component.

// your components array
var myArr = [
    {
        componentName: FieldHeader,
        props: {title:'bla bla},
        showOnDate: '01/01/2019'
    },
    {
        componentName: RadioButton,
        props: {},
        showOnDate: '01/01/2018'
    }
  ]

Now, in the render function:

render(){
    return(
        <div>
            {
                myArr.map((obj, i) => {
                    var ComponentName = obj.componentName;
                    return <ComponentName props={obj.props} />
                })
            }
        </div>
    )
}

Although, obviously this can be simplified into less code, but I've kept it according to the format in your question, to make it easier. Hope that works!

Abhishek Kumawat
  • 780
  • 1
  • 10
  • 25