Saket Patel
Saket Patel

Reputation: 423

How to load content of ReactStrap Tab when it's selected or active?

I am using ReactJS and ReactStrap to create tabs on my page.
When I open the page containing the tabs, the components of all the tabs-content is mounted on the page load but I want the component to load when that particular tab is active.
My Code

ReactStrap Tab Example

Upvotes: 2

Views: 5837

Answers (1)

Sandy
Sandy

Reputation: 11717

Below is the modified code snippet from ReactStrap Tab example. Look for the content inside <TabPane></TabPane>.

export default class Example extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      activeTab: '1'
    };
  }

  toggle(tab) {
    if (this.state.activeTab !== tab) {
      this.setState({ activeTab: tab });
    }
  }
  render() {
    return (
      <div>
        <Nav tabs>
          <NavItem>
            <NavLink
              className={classnames({ active: this.state.activeTab === '1' })}
              onClick={() => { this.toggle('1'); }}>
              Tab1
            </NavLink>
          </NavItem>
          <NavItem>
            <NavLink
              className={classnames({ active: this.state.activeTab === '2' })}
              onClick={() => { this.toggle('2'); }}>
              Moar Tabs
            </NavLink>
          </NavItem>
        </Nav>
        <TabContent activeTab={this.state.activeTab}>
          <TabPane tabId="1">
            { this.state.activeTab == 1 ? <h4>Tab 1 Contents</h4> : null }
          </TabPane>
          <TabPane tabId="2">
            { this.state.activeTab == 2 ? <h4>Tab 2 Contents</h4> : null }
          </TabPane>
        </TabContent>
      </div>
    );
  }
}

Hope it helps.

Upvotes: 7

Related Questions