What could be causing the Material UI tabs to malfunction when dynamically populating the content using a .map function instead of manually inserting it?

I was able to successfully integrate Material UI's tabs by manually adding content, but when I attempted to use a .map function to populate the content from a JSON data source, it stopped working. Can someone help me figure out why? The only change I made was in the MyTabs component where I replaced hard-coded tabs with two .map functions.

Thank you in advance for your assistance!

Here is the sample data:

export const TabsData = [
  {
    tabTitle: 'Tab 1',
    tabContent: 'Hello 1',
  },
  {
    tabTitle: 'Tab 2',
    tabContent: 'Hello 2',
  },
  {
    tabTitle: 'Tab 3',
    tabContent: 'Hello 3',
  },
];

Below is my modified MyTabs component:

import React, { useState } from 'react';

// Material UI
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';

// Data
import { TabsData } from '../../page-templates/full-page-with-tabs/FullPageWithTabsData';

//Components
import TabContentPanel from '../tabs/tab-content-panel/TabContentPanel';

const MyTabs = () => {
  const classes = useStyles();
  const initialTabIndex = 0;
  const [value, setValue] = useState(initialTabIndex);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };
  return (
    <>
     <Tabs
       value={value}
       onChange={handleChange}
       aria-label=""
       className={classes.tabHeight}
       classes={{ indicator: classes.indicator }}
     >
      {TabsData.map((tabInfo, index) => (
        <>
         <Tab
            label={tabInfo.tabTitle}
            id={`simple-tab-${index}`}
            ariaControls={`simple-tabpanel-${index}`}
         />
        </>
       ))}
    </Tabs>
    {TabsData.map((tabInfo, index) => (
        <TabContentPanel value={value} index={index}>
           {tabInfo.tabContent}
        </TabContentPanel>
    ))}
    </>
  );
};

export default MyTabs;

Lastly, here is the TabContentPanel component:

import React from 'react';
import PropTypes from 'prop-types';

// Material UI
import { Box } from '@material-ui/core';

function TabContentPanel(props) {
  const { children, value, index, ...other } = props;
  const classes = useStyles();
  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && <Box className={classes.contentContainer}>{children}</Box>}
    </div>
  );
}

TabContentPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired,
};

export default TabContentPanel;

Answer №1

The issue arises due to the inclusion of extra Fragments (<> and </>) within the Tabs component, which does not support a Fragment as a child:

To resolve this, simply remove those extra fragments:

{TabsData.map((tabInfo, index) => (
  <Tab
    label={tabInfo.tabTitle}
    id={`simple-tab-${index}`}
    key={tabInfo.tabTitle}
    ariaControls={`simple-tabpanel-${index}`}
  />
))}

Also, remember to utilize the key prop with a unique identifier when creating an array of elements. Refer to React's documentation on keys for more information.

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

Interpolating backticks in Javascript allows for constructing a URL containing empty spaces

When utilizing string interpolation with backticks to construct a URL that sends data to a django endpoint, the resulting URL contains unnecessary whitespace and a new line. The problematic JavaScript code is as follows: (function (window, document, unde ...

Is the provided code snippet considered a function-statement, function-expression, and function-expression-statement?

Currently, I am examining some code snippets from the EcmaScript.NET project. Specifically, I am delving into the definitions within FunctionNode.cs file. The comment above the definitions provides a detailed explanation of the three types of functions tha ...

What is the best way to split text copied from a textarea into <p> paragraphs with an equal number of characters in each?

Check out this JSFiddle version I've found a JSFiddle example that seems perfect for my current project needs. However, I'm wondering how to modify the code to ensure that each paragraph is evenly divided with the same number of characters and a ...

Guide on implementing a personalized 'editComponent' feature in material-table

I'm currently integrating 'material-table' into my project. In the 'icon' column, I have icon names that I want to be able to change by selecting them from an external dialog. However, I am encountering issues when trying to update ...

Is it possible to save the project by generating incremental JSON diffs?

In the process of developing a web-based paint program, I have implemented a system where the user's artwork state is saved as a json object. Each time an addition is made to the client's undo stack (which consists of json objects describing the ...

The Zustand store does not reflect changes when the URL is updated

I have a Zustand store connected to the URL. See the code snippet provided below. import { create } from "zustand"; import { persist, StateStorage, createJSONStorage } from "zustand/middleware"; const pathStorage: StateStorage = { ge ...

What is the best way to show toast notifications for various selections in a dropdown menu?

I have a dropdown menu labeled "FavoriteFoods" that includes options such as "Pizza," "Sushi," "Burgers," and "Biryani." When one of these food choices is selected from the dropdown, I would like a toast pop-up to appear with the message "Great choice!" ...

The issue with the Woocommerce quantity increment buttons not functioning properly persists after an AJAX refresh, and the automatic load feature only activates after two

I've hit a brick wall with this particular issue. Many people have suggested solutions, but none seem to be effective for me. My situation probably resonates with quite a few individuals: I decided to customize the WooCommerce quantity input (/global ...

Using ReactJS and Hooks to update state after the .map() function

Trying to update the state using values from an array. Here is an example: const [state, setState] = useState({}); const test = [1, 2, 3]; test.map((item, i) => { setState({ ...state, [`item-${i}`]: item }); }); The current s ...

Develop an XML document with the use of either Javascript or PHP

I have an XML file that contains information about bracelets with photo details. <bracelets> <photo filename="b1.jpg" thumbnail="a1.jpg" description="aa" /> <photo filename="b2.jpg" thumbnail="a2.jpg" description="aa" /> & ...

Incorporating the id attribute into the FormControl element or its parent in Angular 7

I'm attempting to assign an id attribute to the first invalid form control upon form submission using Angular reactive forms. Here is my current component code: onSubmit() { if (this.form.invalid) { this.scrollToError(); } else { ...

What is the best way to retrieve the content from the MongoDB Document in my GET request?

I encountered an issue while attempting to access the Question field within the JSON document body stored in a MongoDB database. Upon executing the GET request, the result displayed as follows: { "_readableState": { "objectMode": true, "highWaterM ...

The node sends a request to the API to retrieve data, which is then stored in an array. Subsequently, another request is

var UfcAPI = require('ufc-api'); var ufc = new UfcAPI({ version: '3' }); const fighterIdList = []; function fetchFighterIds() { ufc.fighters(function(err, res) { for (let i = 0; i < res.body.length; i++) { ...

I'm running into some issues with flexbox and I'm in need of some assistance to find

I positioned two divs next to one another, but instead of each taking up 100vw, they are both sharing 50% of the available space. Is there a solution for this issue? Thank you. Page Image import type { AppProps } from "next/app"; import "./global.cs ...

Tips for setting a unique JWT secret in next-auth for production to prevent potential issues

Is there a way to properly set a JWT secret in NextAuth.js v4 to prevent errors in production? I have followed the guidelines outlined in the documentation, but I am still encountering this warning message without any further explanation: [next-auth][warn] ...

Leveraging the JavaScript NPM module through import functionality

Currently, I am utilizing the kahoot-api NPM module (GitHub, NPM) that requires JavaScript import. (edit: this is a Node.js package. At the time of writing this, I was unaware of the distinction between JS and Node.js, hence the creation of this question). ...

The issue I'm facing with my webpack-build is the exclusive appearance of the "error" that

Hey everyone! I'm currently facing an issue with importing a module called _module_name_ into my React project, specifically a TypeScript project named react-app. The module was actually developed by me and it's published on npm. When trying to i ...

Pretty print error: The specified file or directory does not exist

I recently incorporated eslint and prettier into my existing CSR react project, but when I ran 'npm run prettier' I encountered the following errors. How can I resolve this error? Just so you know, there is a src/App.tsx file contrary to the err ...

What is the best way to create a gradual color change in each individual cell instead of changing all at once?

Looking for some help with a grid I'm working on. I've got the cells changing colors like I want them to, but they're all changing at once. What I really need is for them to light up in a specific order - Yellow, Green, Blue, White, Orange. ...

What methods are available to modify the colors in an Apex bar chart?

Currently, I am in the process of constructing a bar chart using react, mui, and apex-chart. One specific requirement I have is to modify the colors of the bars displayed on the chart. Despite my efforts in attempting various solutions, I have been unsucce ...