EyalS
EyalS

Reputation: 1692

How to instantiate a component from it's class in react native

I'm trying to instantiate a class inside render:

import myFirstComponentfrom './components/myFirstComponentfrom'
import mySecondComponent'./components/mySecondComponent'

  additionalComponents= [
    {component:myFirstComponent},
    {component:mySecondComponent}
  ]
...

render(){
  return (
    <View>
      {additonalComponents[0].component}
      {additonalComponents[1].component}
    </View>
}

unfortunately, it's not working... any idea how this can be done?

Thanks,

Upvotes: 0

Views: 2325

Answers (3)

import {MyFirstComponent} from './components/myFirstComponentfrom';
import {MySecondComponent} from './components/mySecondComponent';

  const additionalComponents = [
    {component:myFirstComponent},
    {component:mySecondComponent}
  ]
...

render(){
  return (
    <View>
      {additonalComponents[0].component}
      {additonalComponents[1].component}
    </View>
}

Your component name should be First Letter Capital, and your import isn't look right. Maybe this will help.

Upvotes: 0

sebastianf182
sebastianf182

Reputation: 9978

React Native does not treat as classes any object that does not start with Uppercase. myFirstComponent should be MyFirstComponent.

Also, the imports are wrong, but I am assuming that is type otherwise that wouldn't even compile.

Upvotes: 0

EyalS
EyalS

Reputation: 1692

Found the answer, using:

render(){
  return (
    <View>
      {React.createElement(this.additionalComponents[0].component, {})}
      {React.createElement(this.additionalComponents[0].component, {})}
    </View>
}

Upvotes: 1

Related Questions