Reem
Reem

Reputation: 150

Dynamically render component based on props

I want to pass the component path from a parent react component to a child react component, and this child component should import the component when the props are ready, but dynamic import rely on that the passed value should be string not a value to resolve at runtime, anything can help me in the

example

<Parent childComponentPath={'../foo/bar'}/>
  cont child = require(this.props.childComponentPath)
  
  <Child/>

Edit: I've tried System.import not working

Upvotes: 0

Views: 2174

Answers (2)

Reem
Reem

Reputation: 150

I've made a separate JS file importing all external components then dynamically send the component name in props to pick the one from this file, also dynamic loading. won't work when the value passed in require is calculated at runtime.

Upvotes: 0

sebastianf182
sebastianf182

Reputation: 9978

This wont work because the packager has already packed the files. The same reason why you cant have dynamic require's.

You would need to modify your logic to accept a string probably and then have like a factory to render a component dynamically. Something like this:

<Parent child='one'/>

render(){

 let Component = One;

switch(this.props.child){
   case: 'one':
      Component: One; break;
    case: 'two':
     Component: Two; break;
}

return <Component/>

}

Upvotes: 1

Related Questions