To handle keyboard events and update the state based on specific key combinations, you need to define a handler method. Take a look at this functional example - https://jsfiddle.net/8laczx6g/ (Please note: click in the result area on the jsfiddle page before pressing any shortcuts):
In this scenario, tabs will switch when you press Ctrl/Cmd + 1
or Ctrl/Cmd + 2
. If you only require the Cmd
key, simply remove || event.ctrlKey
:
class TabsControlledExample extends React.Component {
constructor(props) {
super(props);
this.state = {
activeTab: 'A',
};
this.handleKeyboardEvent = this.handleKeyboardEvent.bind(this);
}
componentDidMount() {
document.body.addEventListener('keydown', this.handleKeyboardEvent);
}
componentWillUnmount() {
document.body.removeEventListener('keydown', this.handleKeyboardEvent);
}
handleKeyboardEvent(event) {
if ((event.metaKey || event.ctrlKey) && event.keyCode === 49) { // CTRL+1 or CMD+1
event.preventDefault();
this.setState({ activeTab: 'A' });
}
if ((event.metaKey || event.ctrlKey) && event.keyCode === 50) { // CTRL+2 or CMD+2
event.preventDefault();
this.setState({ activeTab: 'B' });
}
}
render() {
return (
<Tabs value={this.state.activeTab}>
<Tab label="Tab A" value="A">
<div>
<h2 style={styles.headline}>Controllable Tab A</h2>
<p>
Tabs can be controlled programmatically to assign values for more functionality.
This allows flexibility in tab selection and assignment of different values.
</p>
</div>
</Tab>
<Tab label="Tab B" value="B">
<div>
<h2 style={styles.headline}>Controllable Tab B</h2>
<p>
Another example of a controllable tab. Remember, all tabs must have values assigned to enable selection.
</p>
</div>
</Tab>
</Tabs>
);
}
}