0

Hi Reactjs / Reactstrap Experts-

I am new to ReactJS and Reactstrap and I could not find a live example demonstrating NavItem switching via JS.

I am trying to get Reactstrap's Nav and Navlink toggle from one tab to another based on button clicks. In my code pen page below, when clicking "Go to Tab 2" when on Tab 1 results in a blank view and same happens when I click "Go to Tab 1" button in Tab 2. I am not sure where I could be going wrong.

Here is my JS code and a code pen created based on the below code.

Could you please help?

const { TabContent, TabPane, Nav, NavItem, NavLink, Card, Button, CardTitle, CardText } = Reactstrap;

class App extends React.PureComponent {

  constructor() {    
    super();
    this.state = {
      activeTab: '1'
    };
    this.toggle = this.toggle.bind(this);
    this.switchToTab1 = this.switchToTab1.bind(this);
    this.switchToTab2 = this.switchToTab2.bind(this);
  }

   toggle(tab) {
        if (this.state.activeTab !== tab) {
            this.setState({
                activeTab: tab
            });
        }
    }

  switchToTab2() {
    this.toggle(2);
  }

  switchToTab1() {
    this.toggle(1);
  }

  render() {
    return (
      <React.Fragment>
        <Nav tabs className="card-header-tabs">
          <NavItem>
              <NavLink active={this.state.activeTab === '1'} onClick={() => { this.toggle('1'); }}>
                  Tab 1
              </NavLink>
          </NavItem>
          <NavItem>
              <NavLink active={this.state.activeTab === '2'} onClick={() => { this.toggle('2'); }}>
                  Tab 2
              </NavLink>
          </NavItem>
        </Nav>
          <div className="card-body">
            <TabContent activeTab={this.state.activeTab}>
              <TabPane tabId="1">
                <h1>Content from Tab 1</h1>
                <Button color="primary" onClick={this.switchToTab2}>Go to Tab 2</Button>
              </TabPane>
              <TabPane tabId="2">
                <h1>Content from Tab 2</h1>
                <Button color="primary" onClick={this.switchToTab1}>Go to Tab 1</Button>
              </TabPane>
            </TabContent>
         </div>
      </React.Fragment>
    );  
  }
}

ReactDOM.render(<App />, document.getElementById("app"));
Satya
  • 1,037
  • 3
  • 15
  • 34

1 Answers1

1

You are mixing the string ids with the numeric ids and while comparing you are using === (strict equality check) Reference.

The issue is with your toggle method, You are passing numeric ids. It should be passing string ids and it should work.

switchToTab2() {
   this.toggle(2); // It should be this.toggle('2')
}

switchToTab1() {
   this.toggle(1); // It should be this.toggle('1')
}

Here is the updated codepen link: https://codepen.io/anon/pen/rQEbOJ?editors=0010

Hardik Modha
  • 12,098
  • 3
  • 36
  • 40