Issue with sx prop type error found in the TabPanel component of MUI v5

My first time using MUI with TypeScript has hit a roadblock with the new sx prop. Check out the error displayed by TypeScript in the screenshot linked below: https://i.sstatic.net/JYDTX.png

Interestingly, the error only pops up on the TabPanel Component, even though I've used it seamlessly on other MUI components. Here's my code:

/* eslint-disable react/require-default-props */
import * as React from 'react';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ p: 3 }}>
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
}

function a11yProps(index: number) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`
  };
}

export default function MenteeVolunteerTabs() {
  const [value, setValue] = React.useState(0);

  const handleChange = (event: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
  };

  return (
    <Box sx={{ width: '100%' }}>
      <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
        <Tabs value={value} onChange={handleChange} aria-label="basic tabs example">
          <Tab label="Volunteer" {...a11yProps(0)} />
          <Tab label="Mentee" {...a11yProps(1)} />
        </Tabs>
      </Box>
      <TabPanel value={value} index={0} sx={{ backgroundColor: '#F4F6F7' }}>
        Item One
      </TabPanel>
      <TabPanel value={value} index={1}>
        Item Two
      </TabPanel>
    </Box>
  );
}

Looking for assistance in resolving this error. Any help is appreciated.

Answer №1

TabPanel is not a default component in MUI. It is instead a custom component that needs to be copied from the documentation. (Most likely from this link)

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ p: 3 }}>
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
}

If you want to include the sx prop in your custom component, you can utilize styled():

type TabPanelProps = {
  children: React.ReactNode;
  index: number;
  value: number;
};

const TabPanel = styled((props: TabPanelProps) => {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ p: 3 }}>
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
})<TabPanelProps>();

https://codesandbox.io/s/69726025-material-v5-tabpanel-component-type-error-pbvhr?file=/demo.tsx

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

Tips for creating an onClick event for a React Component that is passed as a prop to another component

I am currently in the process of creating a custom trigger component that can be passed down to another component. My goal is to implement a click event on this trigger component from the receiving component. If you'd like to see a live example, chec ...

Encountering the error message "SyntaxError: Cannot use import statement outside a module" is often linked with the mui-color-input component and Create React App

After integrating the mui-color-input library into my create-react-app project, I encountered a problem with the component test despite the project building successfully. ● Test suite failed to run Jest encountered an unexpected token Jest fai ...

Encountered a Solana Error while handling Instruction 2: custom program error with code 0x1000078

While attempting to create an AMM Pool using the 'ammCreatePool.ts' script from the raydium-sdk repository, I encountered the following error message. I executed the script directly with ts-node src/ammCreatePool.ts and made modifications so that ...

The useEffect hook is failing to resolve a promise

I have received a response from an API that I need to display. Here is a snippet of the sample response (relevant fields only): [ { ...other fields, "latitude": "33.5682166", "longitude": "73 ...

What is the process of importing types in TypeScript?

Here is the export I am working with: import * as jwt from 'jsonwebtoken'; ... export type MyJsonWebToken = typeof jwt; Next, when attempting to use it in my code: export class AuthService { constructor( @Inject(constants.JWT) private ...

Ensuring proper extension of Request headers in Typescript

I am having trouble retrieving the userId from req.headers, how can I fix this issue? Initially, I attempted the following: interface ISpot{ thumbnail: File, company: string, price: number, techs: string } interface IReqCustom<T& ...

Issue with React Material-UI ProgressBar not updating when value is changed

I have a functional component with an MUI progress bar that I want to display. However, when the progress bar loads, it remains at the initial progress level that I set in the first step. Additionally, I am making an API call and processing the results i ...

I'm experiencing an issue with my website where it appears broken when I build it, but functions properly when I use npm run dev in Next

For my project, I have utilized NextJs, Tailwind, React, and Typescript. It is all set and ready to be hosted. After using "output: export" in next.config.js and running npm run build, the process was successful. However, when viewing my website locally, I ...

Filtering an array of objects based on a specific condition in TypeScript

I am trying to filter the array object data where the count of Failed is greater than 0. Unfortunately, the code below is not working as expected. ngOnInit() { this.employeeService.getProducts().subscribe((data:any) => { console.log(data); this. ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

Is there a way to store session variables in Angular without the need to make an API call?

I am currently working with a backend in PHP Laravel 5.4, and I am looking for a way to access my session variables in my Angular/Ionic project similar to how I do it in my Blade files using $_SESSION['variable_name']. So far, I have not discove ...

Utilize React Hook Form to easily reset the value of an MUI Select component

I created a dropdown menu where users can select from "Item 1", "Item 2", and "Item 3". Additionally, there is a "Reset" button that allows users to clear their selection and make a new one. Below is the code I used: import React from ...

An example in Typescript for setting an initial/default value for a data type

Can you create a Type with a default value included? For example: type Animal = { kind : "animal" Legs : number, CanFly: boolean } const monkey: Animal = { Legs: 4, CanFly: false}; //In this line, clients must initialize the same value `kin ...

Styles are not applied by Tailwind to components in the pages folder

NextJS project was already created with tailwind support, so I didn't have to set it up myself. However, when I add className to an HTML element in a component within the pages/ folder, it simply doesn't work, even though the Elements panel in D ...

Is there a way to make the hoverzoom effect only apply to a specific object instead of all objects?

I'm currently troubleshooting my code in order to implement a hover effect on Mui <cards> when a user hovers over the object. I have managed to make it work partially, but the issue is that the effect gets applied to all objects instead of just ...

MaterialUI's Tooltip component is causing warning messages to appear on the client's console

Issues with MaterialUI Tooltip causing warnings in client console "Failed prop type". However, the mentioned props are not used in my components. Warnings displayed on client console: Warning: Failed prop type: The following properties are not supported: ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

Is there a Typescript function error that occurs when attempting to rename a key, stating it "could potentially be instantiated with a different subtype"?

I am currently working on a Mongoify type that accepts a type T, removes the id key, and replaces it with an _id key. type Mongoify<T extends {id: string}> = Omit<T, "id"> & { _id: ObjectId }; function fromMongo<T extends ...

Looking to receive detailed compiler error messages along with full imports in Visual Studio Code for TypeScript?

Currently, I am trying to edit a piece of typescript code in Visual Studio Code. However, I encountered a compiler error message that looks like this: The error states: Type 'import(\"c:/path/to/project/node_modules/@com.m...' is not assign ...

Leveraging the useState hook with an array when retrieving data from the Redux store

When I go to the store, I always make sure to bring my family along with me. Here's how I access my family object from the top: const family:Family = useSelector((state:any) => state.family.family); This object represents my beloved family: addres ...