Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change tabs in react-bootstrap using a button?

How can I change a tab by a click of a button using React/React-Bootstrap? For example, to click on a button and it let me go to the tab selected. Code below:

import React, {Component} from 'react'
import { Tabs, Tab } from 'react-bootstrap';

export default class TabPuzzle extends Component {

constructor(props) {
  super(props);
  this.state = {
    key: 2
  };
 this.handleSelect = this.handleSelect.bind(this)
}
handleSelect(key) {
  alert('selected ' + key);
  this.setState({key});
}
render () {
  return (
    <div>
      <Tabs activeKey={this.state.key} onSelect={this.handleSelect} 
       id="controlled-tab-example">
              <Tab eventKey={1} title="Tab 1"> Tab Content 1 </Tab>
              <Tab eventKey={2} title="Tab 2"> Tab Content 2 </Tab>
              <Tab eventKey={3} title="Tab 3"> Tab Content 3 </Tab>
      </Tabs>
            <button onClick={()=>this.handleSelect("3")}>Go to tab 3</button> 
    </div>
  )
 }
}
like image 912
Phoenix Avatar asked May 24 '17 23:05

Phoenix


1 Answers

this.state.key is a number in your state, but the button is passing a string "3". Pass a number instead, and the <Tabs> component should work as you expect:

<button onClick={()=>this.handleSelect(3)}>Go to tab 3</button> 
like image 174
Ross Allen Avatar answered Oct 04 '22 21:10

Ross Allen