I am new to React and I am trying to get the selected Tab and from a onClick event.
Below is my code along with output.
How would I implement the handleSelect function?
Here is my current code:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {value : 0};
}
getState(){
return this.state.value;
}
setState(state){
this.state = state;
}
handleSelect(index){
console.log('Selected tab: ' + index);
}
render() {
let selectedIndex = this.getState();
return (
<header className="header">
<AppBar title="App Bar" />
<Tabs>
<Tab label="Core Courses" onClick={this.handleSelect(0)} />
<Tab label="Capstone Requirement" onClick={this.handleSelect(1)}/>
<Tab label="Computer Science Electives" onClick={this.handleSelect(2)}/>
<Tab label="Support Courses" onClick={this.handleSelect(3)} />
</Tabs>
</header>
);
}
}
Here is the console log currently when rendered:
Selected tab: 0
Selected tab: 1
Selected tab: 2
Selected tab: 3
Following code will add an "active" class to the selected tab. Hope you can manage it with css, if you have an "active" class inside the selected tab.
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
activeTab : 0
};
this.handleSelect = this.handleSelect.bind(this);
}
handleSelect(index){
this.setState({
activeTab: index
});
}
render() {
let selectedIndex = this.getState();
return (
<header className="header">
<AppBar title="App Bar" />
<Tabs>
<Tab classsName={this.state.activeTab == 0 ? 'active' : ''} label="Core Courses" onClick={this.handleSelect(0)} />
<Tab classsName={this.state.activeTab == 1 ? 'active' : ''} label="Capstone Requirement" onClick={this.handleSelect(1)}/>
<Tab classsName={this.state.activeTab == 2 ? 'active' : ''} label="Computer Science Electives" onClick={this.handleSelect(2)}/>
<Tab classsName={this.state.activeTab == 3 ? 'active' : ''} label="Support Courses" onClick={this.handleSelect(3)} />
</Tabs>
</header>
);
} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With