Execute a simulated click on the Material-UI Tabbar using a programmatic approach or keyboard shortcut

In my electron/react application, I am implementing Material UI tabs in the following manner:

        <Tabs>
          <Tab label="View1" >
            <View1 />
          </Tab>
          <Tab
            label="View2">
            <View2 />
          </Tab>
          <Tab label="View3" >
            <View3 />
          </Tab>
          <Tab label="View4" >
            <View4 />
          </Tab>
        </Tabs> 

Now, I want to implement a shortcut that changes the active view. For example, if Tab1 is currently active showing View1, pressing Cmd + 2 should switch to Tab2 and render View2 as if it was manually clicked. I've tried different approaches but I'm struggling with the syntax of Material UI.

Answer №1

If you want to specify which tab opens in the Tabs component, simply send a prop like this:

    <Tabs value={this.state.tabIndex}>
      <Tab label="View1" >
        <View1 />
      </Tab>
      <Tab
        label="View2">
        <View2 />
      </Tab>
      <Tab label="View3" >
        <View3 />
      </Tab>
      <Tab label="View4" >
        <View4 />
      </Tab>
    </Tabs> 

To change the selected tab programmatically, add a method as follows:

changeTab = (tabIndex) => {
  this.setState({ tabIndex })
}

Answer №2

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

Answer №3

Click here to visit the Tabs property section on material-ui.com, where you can find an explanation of the value property -

The value prop makes Tabs controllable and selects the tab with a matching value.

This concept is further illustrated in the following code snippet -

// ...within a component
state = {
    selectedTab: "tab1" // default selection is tab1.
};

handleTabChange = (tabValue) => {
    this.setState({selectedTab: tabValue});
};

// In the render method
<Tabs value={this.state.selectedTab} onChange={this.handleTabChange}>
    <Tab label="Tab 1" value="tab1">
        <div>...</div>
    </Tab>
    <Tab label="Tab 2" value="tab2">
        <div>...</div>
    </Tab>
<Tabs>

By setting setState({selectedTab: ""}), you can dynamically choose which tab to select programmatically.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to access a user's public information using Instagram's API

I've spent the past week trying to create a simple Instagram preview application that should show a user's public data such as username, followers, following, and profile picture URL, but unfortunately, I haven't been able to find a solution ...

AngularJS view is not refreshing

I am facing an issue with updating a view via a controller that fetches data from a service. Despite changing the data in the service, the view does not reflect these updates. I have created a simplified example from my application, which can be found here ...

Utilizing Object-Oriented Programming to organize and store data within a class object

After successfully running a class to fetch all data and store it in an object, I noticed that the object (AllOptions) is undefined. I have attempted to find a suitable solution but have been unsuccessful. router.get('/:category', (req, res) =& ...

Checking for null properties in Typescript objectsorHow to verify if a

What is a simple way to determine if the properties of an object in TypeScript are nullable? For example export default interface UserDto{ ID?:int; USER_NAME?:string; FIRST_NAME?:string; LAST_NAME?:string; USER_ROLE?: ...

What could be the reason for the data being retrieved but not showing up on the web page?

When fetching data from an API, I encounter a problem where the Loader displays but the data never shows up on the page. The inconsistency of this behavior is puzzling to me. This issue seems to be more prevalent on smartphones than on computers. useEffec ...

Retrieve a JSON response from within a schema housed in MongoDB

I have a document structure that looks like this: { "id": "someString", "servers": [ { "name": "ServerName", "bases": [ { "name": "Base 1", "status": true }, { "name": "Base 2", ...

Develop a specialized WordPress widget featuring several unique text areas for enhanced customization

class ad_widget extends WP_Widget { function __construct() { $widget_ops = array( 'classname' => 'ad-widget-container', 'description' => __( ' Ad WIDGET' ) ); parent::__construct( 'ad-widget', ...

Storing client time data in a database using Node.js

Just starting out with Node.js so bear with me while I learn the ropes. I successfully set up a basic TCP server using the guide here In my current project, users will connect to the server from a web browser and I'm interested in capturing the TCP ...

What is the best way to store a range object obtained from getSelection in order to recreate it on a separate page load?

My goal is to develop a web application that enables users to highlight selected text on a webpage with the click of a button. I want these highlights to persist even when the user returns to the page. So far, I have achieved: var selectedRange = documen ...

Using javascript to extract values from nested JSON structures without prior key knowledge

My JSON data is structured as follows: {"sensors": {"-KqYN_VeXCh8CZQFRusI": {"bathroom_temp": 16, "date": "02/08/2017", "fridge_level": 8, "kitchen_temp": 18, "living_temp": 17, ...

Ways to Conceal <div> Tag

I need help with a prank .html page I'm creating for a friend. The idea is that when the user clicks a button, a surprise phrase pops up. I have managed to hide and unhide the phrase successfully using JavaScript. However, my issue is that when the pa ...

Ways to transmit the appropriate model

Using AJAX, I am sending a model to the server via a POST request. I have defined a model and a controller method for processing it. public class TestDto: BaseDto { [Required] public ProductGalleryDto GalleryProduct { get; set; } public int ...

The challenge of mapping React Select

I have implemented react-select in my project and I am using it within a map function like this: renderItems() { this.props.items.map(item => ( <Select id="options" value={this.state.optionSelected} onChange={this.onChangeOpt ...

The Express.js application functions properly on a local environment, but encounters issues when deployed on Heroku

Currently, I am experiencing an issue with deploying a music visualizer that I created. It seems to work perfectly in all scenarios except when I click on a song to play from the search bar, where I keep encountering a '503 (Service Unavailable)' ...

Adding values to a knockout data table without refreshing the page

I am currently experiencing difficulties with refreshing my knockout.js DataTable. I have a data table that loads correctly on page load using the attached function method. I also have multiple buttons (Display All, Allowed, Not Allowed) that display the t ...

Can I apply MUI's touch ripple effect to a div element?

After browsing through various responses to similar queries, I noticed that most of them are outdated and no longer applicable to the latest version of MUI. I'm looking for a way to add the touch ripple effect to a div element, but I can't use a ...

How can the token be verified when authorizing Google OAuth 2.0 on the server side?

Unable to validate the user token ID on the server side despite following Google's guide at https://developers.google.com/identity/sign-in/web/backend-auth In JavaScript, I retrieve the id token and send it to the server: var googleUser = auth2.cur ...

Creating dynamic Ionic slides by fetching data from a database

I am currently experimenting with Ionic. Web development is not my strong suit, so I may be a bit off the mark. However, I would like to retrieve data from an SQLite database and display it on an ion-slide-box. Here is what I have attempted: function sel ...

Revamping the login interface for enhanced user

Whenever I attempt to login by clicking the login button, there seems to be an issue as it does not redirect me to any other page. Instead, I am left on the same page where I initially clicked the button. The intended behavior is for users to be redirected ...

Deploying a ReactJS application on AWS Elastic Compute Cloud (EC2) with a wildcard SSL

After developing a reactjs app with a .net core web API as the backend, I successfully hosted it on a Windows server using IIS with http. However, when attempting to use a wildcard SSL certificate, an error appeared in the Chrome console: "Failed to loa ...