6

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>
  )
 }
}

1 Answer 1

5

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> 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.