0

I have an array as such:

export const options = [
    {id: 1, name='ComponentOne'},
    {id: 2, name='ComponentTwo'},
]

Then I have my components:

export const ComponentOne = props => (<div>{this.props.content}</div>)
export const ComponentTwo = props => (<div>{this.props.content}</div>)

Then I have my view:

export class MyView extends React.Component{
    constructor(props){
        super(props);
        this.state = {};
    }
    render(){
        return(
            <div>
                {options.map( obj => <obj.name/> )
            </div>
        )
    }
}

I would like to dynamically render these components but have no idea how to.

3
  • 1
    What if you use the component itself instead of the name in options? {id: 1, name=ComponentOne}. Should it work? Commented Dec 26, 2017 at 11:55
  • do you know all the component names that could be in this array? If yes, why not use a switch statement? Commented Dec 26, 2017 at 12:05
  • Check this stackoverflow.com/questions/47649723/… Commented Dec 26, 2017 at 12:42

1 Answer 1

1

Instead of keeping the name of the component class why not keep the class itself. Like so:

const options = [
    {id: 1, componentClass: ComponentOne},
    {id: 2, componentClass: ComponentTwo}
];

export class MyView extends React.Component{
    constructor(props){
        super(props);
        this.state = {};
    }
    render(){
        return(
            <div>
                {
                  options.map(obj => {
                    const Class = obj.componentClass;

                    return <Class />;
                  })
                }
            </div>
        )
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

How would I pass the props to <Class/>?
What are the props that you which to pass
for example the id of MyView Parent Component Okay thanks a lot. This worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.