CJLopez
CJLopez

Reputation: 5815

Setting up tabs on state

I'm trying to setup the tabs a React component in the parent component states, something like this

import React from 'react';
import Component1 from '../myChildComponents/Component1';
import Component2 from '../myChildComponents/Component2';
import Component3 from '../myChildComponents/Component3';

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tabs: [
        {id: '1', text: 'Tab 1', component: Component1},
        {id: '2', text: 'Tab 2', component: Component2},
        {id: '3', text: 'Tab 3', component: Component3},
      ]
    }
  }
  
  render() {
    return (
      <!-- All the other stuff goes here, like the tabs headers -->
      <TabContent>
      {
        this.state.tabs.map((t, i) => 
          <TabPane key={i} tabId={t.tabId}>
            <t.component {...this.props.data}>
          </TabPane>
        )
      }
      </TabContent>
    )
  }
}

Can something like this be achieved? I already tried using the React.createComponent function, but this worked

Edit1: Updated to reflect current test implementation, still seeing the following message on the console

Uncaught (in promise) Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render metho

Upvotes: 2

Views: 112

Answers (1)

Ahmad
Ahmad

Reputation: 72653

Yeah you can use a component like that.

 render() {
    return (
      <!-- All the other stuff goes here, like the tabs headers -->
      <TabContent>
      {
        this.state.tabs.map((t, i) => 
          <TabPane key={i} tabId={t.tabId}>
            <t.component {...t.data}/>
          </TabPane>
        )
      }
      </TabContent>
    )
  }

Only thing you need to change is:

  • your object key is component; lower case
  • you need to set the props by using the spread operator on the t.data object: {...t.data}

Upvotes: 1

Related Questions