Reputation: 766
I need to dynamically inject a component at runtime with react native. I receive data from an API endpoint, which I then set in state. There are currently three possibilities -> EventModal, ArticleModal, NewsModal. I import all three. A simplified example of what I'm trying to do is below....
render() {
let Page = { component: this.state.currentModal + "Modal" };
return (
<Page.component />
);
}
That is similar to Dynamically Rendering a React component
But unfortunately doesn't seem to working (both examples in and out of brackets) as I receive the error "expected a component class, got EventModal". Similarly I tried with the object syntax
render() {
let Page = this.state.currentModal + "Modal";
return (
<Page />
);
}
However same result. Any suggestions?
Upvotes: 5
Views: 3939
Reputation: 9978
This happens because you are adding the 'Modal' which turns the variable into a string so is not a component. Also, React Native does not treat any variable as a Component unless it has an uppercase at the beginning.
So try something like this (you will have to add the others as well):
import EventModal = require('./EventModal');
render(){
let Component = null;
switch(this.state.currentModal){
case: 'EventModal':
Component = EventModal;
break;
}
return <Component/>;
Upvotes: 3
Reputation: 7382
You need to import/require EventModal. So in that case it's better not to use string and use the reference
var EventModal = require('../components/EventModal');
render() {
let Page = EventModal;
return (
<Page />
);
}
Upvotes: 0