How to call an event on tabs changed in react-bootstrap

<Tab.Container id="" defaultActiveKey={key} onSelect={this.handleSelect}>
   <Nav variant="tabs">
        <Nav.Item>
        <Nav.Link eventKey={'1'}>Staking</Nav.Link>
        </Nav.Item>

        <Nav.Item>
        <Nav.Link eventKey={'2'}>Providers</Nav.Link>
        </Nav.Item>

        <Nav.Item>
        <Nav.Link eventKey={'3'}>Overview</Nav.Link>
        </Nav.Item>
    </Nav>
    <Tab.Content>
        <Tab.Pane eventKey={'1'}>
         <Row>
             <Col>
              1111
             </Col>
         </Row>
        </Tab.Pane>
    </Tab.Content>
    <Tab.Content>
        <Tab.Pane eventKey={'2'}>
        <div>22222</div>
        </Tab.Pane>
    </Tab.Content>
    <Tab.Content>
        <Tab.Pane eventKey={'3'}>
        <div>333</div>
        </Tab.Pane>
    </Tab.Content>
 </Tab.Container>

Now in your state add 'key' field with initial value '1'

  constructor(props) {
    super(props);
    this.state = {
     key: '1'
    };
  }

Then write a function

  handleSelect = (key) => {
      console.log(key,';;',typeof key)
      if(key === '1') {
          console.log('ll', key)
      } else if(key === '2') {
        console.log('ll', key)
      } else if(key === '3') {
        console.log('ll', key)
      }
  }

Initially when the page loades, the function is not called so you can make API calls or any thing you want to do in the 1st tab, in componentDidMount or any other function and place it in the 1st tab i.e where I've written 1111,after this when you click another tab, handleSelect function is called and based on key value with use if..else statement to perform specific task for specific tab.

Hope this helps. If any issue please let us know in the comment section.


You need to use onSelect in the Tabs component.

Like this:

<Tabs defaultActiveKey={1} onSelect={this.handleSelect()}>
    <Tab eventKey={1} title="Log in">
        {/* Irrelevant code */}
    </Tab>
    <Tab eventKey={2} title="Sign up">
        {/* Irrelevant code */}
    </Tab>
</Tabs>

And then make this your handleSelect function:

handleSelect(key) {
    if (key === 1)
        this.setState({ heading: "Log in" })
    else
        this.setState({ heading: "Sign up" })
}