ibob
ibob

Reputation: 50

How to dynamically declare components

With:

this.props.components = [{component: input}, {component: button}]

In this code:

    var React = require('react');

var form = React.createClass({
    render: function () {
        var components = [];
        var component = null;
        //console.log(this.props.components);
        for (var i=0; i < this.props.components.length; i++) {
            console.log(this.props.components[i]);
            component = this.props.components[i].component;
            components.push(<component />);
        }
        console.log(components);
        return (
            <div>
                {components}
            </div>
        );
    }
});

module.exports = form;

My problem is that instead of render a div containing an input and a button it render two void elements of type "component". Any ideas?

Upvotes: 2

Views: 106

Answers (1)

Jim Skerritt
Jim Skerritt

Reputation: 4596

If you've already passed in your components to your form class like this:

<Form
    components={[
        {component: <input />},
        {component: <button></button>}]}
/>

then you don't need to wrap <component /> in JSX like that, since you've already rendered your components. Just do:

for (var i = 0; i < this.props.components.length; i++) {
    component = this.props.components[i].component;
    components.push(component);
}

Upvotes: 1

Related Questions