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 retrieve information from the database during the http.get request

Hey everyone, I've encountered an issue that I need help with. I'm working on retrieving data from a database using an HTTP call and then returning it to the front end. Here's what I have so far: app.get('/contentHandler/post/frontPage ...

Encountering vulnerabilities during NPM installation, attempting to fix with 'npm audit fix' but unsuccessful

While working on my react project, I decided to incorporate react-icons by running npm install react-icons in the command prompt. However, after some time, the process resulted in the following errors: F:\Areebs\React JS\areeburrub>npm in ...

Is it possible to add animated text using anime.js?

var elements = document.querySelectorAll('.content'); anime({ targets: elements, content: 100, }); <script src="https://raw.githubusercontent.com/juliangarnier/anime/master/lib/anime.min.js"></script> <span class="content"> ...

How can I display a minimal number of rows in a Multiline TextField in Material UI with ReactJS without any scrolling beyond that limit?

When using Material UI Texfield for multiline input, I am looking to display a minimum of 3 rows initially and then have the text area expand further without showing a scroll bar if the content exceeds 3 rows. I attempted the following: <TextFi ...

Learn how to incorporate the dynamic array index value into an Angular HTML page

Exploring Angular and facing a challenge with adding dynamic array index values in an HTML page. Despite trying different solutions, the answer remains elusive, as no errors are being thrown. In TypeScript, I've initialized an array named `months` wh ...

Effortlessly uploading large files using axios

I am currently facing an issue and I am seeking assistance. My goal is to implement file chunk upload using axios, where each chunk is sent to the server sequentially. However, the requests are not being sent in order as expected. Below is a snippet of m ...

Issues arise when attempting to manipulate the DOM with ng-view in AngularJS

Apologies for not providing the code due to its length. I have a simple application with a single module, controller, and ng-view/routProvider. In my controller, when I use console.log(angular.element('div').length), it correctly shows that ther ...

What is preventing me from retrieving an ID value within an IF condition?

I'm trying to create a script that only allows devices with matching IP addresses, but I'm having trouble using an if statement. Whenever I include x.id inside the statement, it doesn't seem to work... any suggestions? <html> <sc ...

Exploring the intricacies of AngularJS: Unraveling the

Iā€™m currently diving into the world of Angular and grappling with retrieving JSON data. However, the concepts of $scope and $http are still a bit fuzzy for me. Can someone provide a clear explanation of what $scope and $http mean in this context? Below ...

Eradicating a character from an Object using Jquery/Javascript

Looking at this code snippet, it appears that the 3rd column is not calculating correctly due to a comma being present in one of the values. Is there a way to rectify this issue without directly removing the comma? I am aware that using .replace(/,/g,&apos ...

Maximizing the potential of the autocomplete component in ReactJS: Setting multiple values

Looking for assistance with setting multi selected values for autocomplete in a ReactJS project. The components being used are from Material-UI library. For example, as shown above, the first data is related to one user and the second data is from another ...

What steps can be taken to have Eslint/Prettier report errors and warnings within a CI environment?

Recently, I encountered an issue with my Vue app where I am using Eslint with Prettier. Even though I have set up a Github action to check the code style, running npm run lint -- --no-fix only logs the warnings and does not cause the workflow to fail. I r ...

Changes will not reflect until a re-deployment is done on Next.js 13 and Sanity

Hey there! Currently, I'm using Next.js version 13 with server components by utilizing the /app directory along with Sanity Studio. Here's a snippet of my code: const Page = async () => { const query = groq`*[_type == "university"] ...

Animate an image to the right when clicked, then return it to the left with a second click

Seeking help with animating a set of images to move individually 300px right on first click, and then 300px left when clicked again. I'm currently facing an issue where my code is not working. It could be due to A) syntax errors or B) the images not ...

Is there a way to store JSON data in a constant variable using Node Fetch without encountering the error TypeError [ERR_INVALID_URL]: Invalid URL?

In my current NodeJS project, I am working on extracting data from a JSON file and then sending it to a constant variable in my app2.mjs. The goal is to organize this data into an array of objects and eventually save it into a database. However, when tryin ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

The webpage is displaying an error stating that "<function> is not defined."

I recently duplicated a functional web page into a new file on my site. However, after adding a new function and removing some HTML code, the JavaScript function no longer runs when clicking one of the two buttons. Instead, I receive the error message "Beg ...

How can I access a component variable within a foreach loop in Typescript?

Can anyone please explain how I can access a component variable within a foreach loop? Check out my code on Plunker public exampleVariable:number; test(){ console.log('fired'); var x =[1,2,3,4]; x.forEach(function (e){ th ...

Add a border to the 'contenteditable' class in a Bootstrap table after it has been modified

Looking for help with JavaScript and jQuery! I have a script that creates an HTML table from a CSV file, using Bootstrap for styling. I want to add CSS or a border to a table cell after it has been edited, but my jQuery attempts haven't worked. Any su ...

Implementing server-side middleware for individual routes in Next.js

I am currently exploring options for executing code upon the initial page load of each request. My goal is to determine the domain of the request and redirect to a specific section of the website based on this information. One possibility I have considere ...