Troubleshooting the failure of implementing react hooks useState within a material-ui Tab container

Recently, I have been experimenting with implementing react-hooks useState in material-ui/tabs component. While I have been successful in using the handleChange function, I am eager to explore and master the use of hooks in this scenario. Interestingly, my useState is functioning well for input fields but not when it comes to handling onChange event for material-ui tabs. Below is a snippet of code from my current setup:

const [value, setValue] = useState(0)

<Tabs
   value={value}
   onChange={(event) => setValue(event.target.value)}
   variant="scrollable"
   scrollButtons="on"
   indicatorColor="primary"
   textColor="primary"
 >
     <Tab label="All" />
         {subjects.map((subject) => (
             <Tab label={subject.subjectName} />
      ))}
 </Tabs>

In an attempt to troubleshoot, I introduced console logging via useEffect which revealed that the onChange was returning undefined.

Answer №1

One thing that stands out to me is the

onChange={(event) => setValue(event.target.value)}

should actually be:

onChange={(event, newValue) => setValue(newValue)}

In this scenario, the event represents a click event and the target refers to the specific DOM element that was clicked, which could vary among elements like span or button within the Tab. Unlike traditional input elements, none of the elements within the Tab have a value property, hence Material-UI sends the value separately as an argument to the onChange function.

Below is the relevant code snippet from the Tab component:

  handleChange = event => {
    const { onChange, value, onClick } = this.props;

    if (onChange) {
      onChange(event, value);
    }

    if (onClick) {
      onClick(event);
    }
  };

The correct way to use the onChange function is detailed in the Tabs props documentation: https://material-ui.com/api/tabs/#props

onChange func Callback fired when the value changes. Signature:

function(event: object, value: number) => void

A live example based on your code can be found here:

https://codesandbox.io/s/l5y4yzzlx9?fontsize=14

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

Error in React-router: "Attempting to access property 'transitionTo' which is undefined"

I am utilizing webpack, ES6, react-router library, and the Link component for handling my links. I am trying to transition with the parent div of the link element, but every time I click on the div, I encounter this error: Uncaught TypeError: Cannot read ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

I am attempting to transfer information from one page to another in Next.js, but unfortunately, I am experiencing difficulties in

Encountering the following error message: "Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead." Any assistance will be greatly appreciated. export default func ...

Insert a JSX element into the body of a webpage using React JSX

Is there a way to dynamically add elements to the end of the body using vanilla JavaScript? const newRecipe = <div id = "container"> <div className="recipe App" id="four" onClick={this.toggleRecipeList.bind(this)}>{this.state.recipeName} < ...

Adding a <link> tag with a specific onload attribute in the <head> using Next.js

While working on a Next.js project, I am trying to include the following HTML content within the <head>: <link href="..." rel="stylesheet" media="print" onload="this.media='all'" /> The code I ...

Running a Custom Tab Component in a React Application

I am currently facing an issue with my React app that has multiple tabs. When I click on a specific tab, I want only that tab to render, but currently all tabs are rendering when I click on one. I have used console.log to confirm that all tabs are indeed r ...

Guide on how to switch a class on the body using React's onClick event

There's a button in my code that triggers the display of a modal-like div element. When this button is clicked, I aim to apply a class to the body element; then when the close button is clicked, I'll remove this class. I'm looking for guid ...

What causes the circular progress bar to disappear when hovering over the MUI React table?

My goal was to create a table with a CircularProgressBar that changes its background color from orange to dark blue when hovering over the row. However, despite my efforts, I couldn't get it to work as intended. Additionally, I wanted the progressBar ...

Challenges when it comes to exporting files using Firebase Cloud Functions

I've been working with Firebase Cloud Functions using JavaScript, but I'm encountering issues with the import and export statements. Is there a solution to replace them? const firebase = require('firebase'); const config = { apiKe ...

"Exploring the process of overloading the CSS for a Material Switch

I am attempting to customize the MuiSwitch-track class of a switch, but so far my efforts have been unsuccessful. What I really want to do is customize the track for a specific switch only. I attempted using "@global": { ".MuiSwitch-track": { b ...

What are the steps to effectively utilize data retrieved from readFragment using Apollo?

Once a user logs in, the system returns a jwt token and a user object containing the id and firstName, which are then stored in cache (refer to the image link provided below). https://i.stack.imgur.com/oSXZ5.png I aim to retrieve the user information fro ...

What reasons could lead to useSWR returning undefined even when fallbackData is provided?

In my Next.js application, I'm utilizing useSWR to fetch data on the client-side from an external API based on a specified language query parameter. To ensure the page loads initially, I retrieve data in a default language in getStaticProps and set it ...

Triggering two function calls upon submission and then waiting for the useEffect hook to execute

Currently, I am facing a challenge with form validation that needs to be triggered on submit. The issue arises as some of the validation logic is located in a separate child component and is triggered through a useEffect dependency from the parent componen ...

Trouble with MUI breakpoints interacting with a collapsible drawer

Having an issue with my drawer that I modified to have a default width of 450px and a max width of 800px. The xs value is set to 6 and sm to 4, but it doesn't change as expected. It remains at 4 regardless of whether I expand it to 800px or keep it at ...

Index.js is dynamically importing a .tsx file post-build, with a specific focus on Windows

While working on my project, I decided to customize a module by cloning it and making some changes. After installing the dependencies and building it, I encountered an error when trying to run it. The error message stated: Error: Unable to resolve module & ...

Tips for expanding an input to fit the width of a div without altering the dimensions of a preceding span element

Let me explain, I have a form that includes a span and an input: <form onSubmit={e => handleSubmit(e)}> <Box className='form_box'> <span> <a href="/cd ...

Webstorm showcases files with similar content in a distinct manner

In Webstorm, everything is color-coded based on whether it is a function, object, etc. I am working with JavaScript. I have noticed that in two different files, the same line of code looks differently: var Comment = React.createClass({ In file 1: "var" ...

The npm postinstall script will only execute if no packages are currently being installed

I made a mistake The reason behind why running npm install whatever results in the deletion of the node_modules/- folder is not what I initially thought. I mistakenly believed it executed the preinstall script but skipped the postinstall script, which was ...

Tips for making a horizontal grid layout with three items in each row

I have a scenario where I need to render a group of Player components using map() loop, and I want them to be displayed horizontally side by side using a Grid component from material-ui. Currently, the components are rendering in a vertical layout: https ...

The OpenWeather API seems to be experiencing some issues when being used in a React JS application, as the URL is displaying data

import React, { Component } from 'react' import './App.css'; import axios from 'axios' const api = axios.create({ baseURL: 'https://api.openweathermap.org/data/2.5/weather?q=Karachi&appid=e3f8864274e67280b3ee8eb501d ...