Closeable MUI React Tabs

297 Views Asked by At

Here I have use MUI tabs and added a X button to it, I am having trouble making the tabs closeable, was wondering for help and guidance so that I can close tabs. I have tried different ways but no success.

Code

I tried setting new values but to no avail.

1

There are 1 best solutions below

0
On

I cannot reproduce your code since not enough information is given. I made a generic example using standard HTML elements to demonstrate the problem.

Based on the code, you keep track of the open tab by retaining an index with the use state hook. But as far as I can tell, you do not keep track of the existing tabs. If a user is to close a tab, the component's state must be updated to reflect that change. For example, if you have an array of tabs, you would use the useState hook to preserve this array across rerenders. Once handleClose is called, we need to create a new array without the element that handleClose was called on to prevent it from being rendered.

You can see in my example, when closeTab is called, an index is passed in to the function, and a brand new array is created with the item at that index excluded, leading to the close effect.

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

const TabsMap = () => {
  const [tabs, setTabs] = useState(Array.from(Array(10).keys()));

  const closeTab = (i) => {
    if (i === 0) {
      if (tabs.length > 1) {
        setTabs(tabs.slice(1, tabs.length));
        return;
      }

      setTabs([]);
      return;
    }

    if (i === tabs.length - 1) {
      setTabs(tabs.slice(0, tabs.length - 1));
      return;
    }

    setTabs([...tabs.slice(0, i), ...tabs.slice(i + 1, tabs.length)]);
  };

  return (
    <div>
      {tabs.map((k, i) => (
        <button onClick={() => closeTab(i)}>{k}</button>
      ))}
    </div>
  );
};

const App = () => {
  return <TabsMap />;
};

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);