Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Tabs] Add selected prop for easy integration with routing libraries #44844

Closed
itayperry opened this issue Dec 22, 2024 · 7 comments
Closed

[Tabs] Add selected prop for easy integration with routing libraries #44844

itayperry opened this issue Dec 22, 2024 · 7 comments
Assignees
Labels
component: tabs This is the name of the generic UI component, not the React module!

Comments

@itayperry
Copy link

itayperry commented Dec 22, 2024

Summary

Hi,
First of all, I do not wish to waste the maintainers' time, I just think this matter will be meaningful for the front-end community :)

The subject at hand is allowing the tabs to be used with navigation in libraries like React Router - making each tab know if it's active using the routes "isActive" prop.

I will start by showing an example of a navigation with different MUI components -
<ToggleButtonGroup/>
combined with
<ToggleButton/>

First, this is a part of an example router - a route that has 3 sub-routes:

.
.
.
{
    path: "incidents",
    element: <>something... <Outlet /></>,
    errorElement: <>some error</>,
    children: [
        { 
            index: true, 
            element: <Navigate replace to="main-events" />, },
        {
            path: "main-events",
            element: <SimulationIncidentsCards />,
        },
        {   path: "all-events", element: <AllEventsTable /> },
        {
             path: "map-display",
             errorElement: "some-error",
             element: <SimulationMap />,
         },
    ],
},
.
.
.

This is a component that toggles between the routes,
each is aware of the isActive prop and knows whether it is selected or not.

import {
  ToggleButton,
  ToggleButtonGroup,
} from "@mui/material";
import { NavLink } from "react-router-dom";


type IncidentDisplay = {
  name: string;
  to: string;
  icon: JSX.Element;
};
const simulationDataPageSubRoutes: IncidentDisplay[] = [
  {
    name: "Main-Events",
    to: "./main-events",
    icon: <GridViewOutlinedIcon fontSize="small" />,
  },
  {
    name: "All-Events",
    to: "./all-events",
    icon: <TableViewOutlinedIcon fontSize="small" />,
  },
  {
    name: "Events-Map",
    to: "./map-display",
    icon: <MapTwoToneIcon fontSize="small" />,
  },
] as const;

function HeaderToggler() {
  return (
    <ToggleButtonGroup
      color="primary"
      // value={alignment}
      exclusive
      // onChange={handleChange}
      aria-label="Platform"
      size="small"
    >
      {simulationDataPageSubRoutes.map((subRoute) => {
        return (
          <NavLink to={subRoute.to} style={{ all: "unset" }} key={subRoute.to}>
            {({ isActive, isPending }) => (
              <ToggleButton
                size="small"
                aria-label={subRoute.name}
                selected={isActive}
                disabled={isPending}
              >
                {subRoute.icon}
              </ToggleButton>
            )}
          </NavLink>
        );
      })}
    </ToggleButtonGroup>
  );
}

This code is extremely comfortable and easy, but unfortunately cannot be implemented with Tabs/Tab.
A tab can never know whether it is selected or not, and it depends on its parent, the <Tabs> component.

Examples

No response

Motivation

I was just thinking it will be really easy and fun to allow tabs to do what button-toggle(rs) already do..

Plus, many SPA React projects are written with React-Router / TanStack-Router, and I truly believe this will be extremely helpful and widely used in the community 🎄

Search keywords: tab

@itayperry itayperry added the status: waiting for maintainer These issues haven't been looked at yet by a maintainer label Dec 22, 2024
@aarongarciah aarongarciah changed the title Adding a "selected" prop for Tab component to enable easy integration with routing libraries like React Router / TanStack Router [Tabs] Add selected prop for easy integration with routing libraries Dec 24, 2024
@aarongarciah aarongarciah self-assigned this Dec 26, 2024
@aarongarciah
Copy link
Member

aarongarciah commented Dec 26, 2024

Hey @itayperry, thanks for contributing. Can you provide the API you envision to support your use case? Take into account that Material UI components can't directly integrate with libraries like React Router or TanStack Router because we can't have access to the state coming from those libraries out of the box. There will be always a small amount of glue code that you'll need to connect these libs with Material UI.

Have you taken a look at this guide? https://mui.com/material-ui/integrations/routing/#tabs

I just created this naive example on how you might use useLocation or other routing libs APIs to get the current tab to control the value passed to the Tabs components: https://codesandbox.io/p/sandbox/keen-fire-xh4755?file=/src/Demo.tsx:11,11 In the example, the third tab uses the component to render the tab as a NavLink from React Router to showcase how you might leverage it to have more control over the rendering of a particular tab.

@aarongarciah aarongarciah added component: tabs This is the name of the generic UI component, not the React module! status: waiting for author Issue with insufficient information and removed status: waiting for maintainer These issues haven't been looked at yet by a maintainer labels Dec 26, 2024
Copy link

github-actions bot commented Jan 3, 2025

Since the issue is missing key information and has been inactive for 7 days, it has been automatically closed. If you wish to see the issue reopened, please provide the missing information.

@github-actions github-actions bot closed this as completed Jan 3, 2025
@itayperry
Copy link
Author

HI there @aarongarciah,
I will try to convince you to reopen this request :)
I have seen the MUI examples for doing such a thing, and of course, thank you for taking the time to make a CodeSandbox example! 🚀

There will be always a small amount of glue code that you'll need to connect these libs with Material UI.

I understand it but as a developer I always try to find a way to make things simpler.

Using the useLocation() adds another layer of complexity that would be unnecessary if we could do something like this (very simple and generic):

const childRoutes = [
  {
    name: "INBOX",
    to: "./inbox",
  },
  {
    name: "DRAFTS",
    to: "./drafts",
  },
  {
    name: "TRASH",
    to: "./trash",
  },
] as const;

function MyTabsToggler() {
  return (
    <Tabs color="primary" aria-label="basic tabs example">
      {childRoutes.map((subRoute) => {
        return (
          <NavLink to={subRoute.to} style={{ all: "unset" }} key={subRoute.to}>
            {({ isActive, isPending }) => (
              <Tab
                value={subRoute.name}
                aria-label={subRoute.name}
                selected={isActive} 
                disabled={isPending}
              />
            )}
          </NavLink>
        );
      })}
    </Tabs>
  );
}

This code doesn't work because the tab doesn't have a way (like a selected prop) to know it's selected.

Here's an example of doing it without tabs, using ToggleButtonGroup (there's also a CodeSandbox):

https://codesandbox.io/p/sandbox/holy-meadow-tn5vdz?file=%2Fsrc%2FDemo.tsx%3A81%2C1-103%2C2&workspaceId=ws_WogxmRaYV3mxmRDct9aYMn

const childRoutes = [
  {
    name: "INBOX",
    to: "./inbox",
  },
  {
    name: "DRAFTS",
    to: "./drafts",
  },
  {
    name: "TRASH",
    to: "./trash",
  },
] as const;
function HeaderToggler() {
  return (
    <ToggleButtonGroup color="primary" exclusive>
      {childRoutes.map((subRoute) => {
        return (
          <NavLink to={subRoute.to} style={{ all: "unset" }} key={subRoute.to}>
            {({ isActive, isPending }) => (
              <ToggleButton
                size="small"
                value={subRoute.name}
                aria-label={subRoute.name}
                selected={isActive}
                disabled={isPending}
              >
                {subRoute.name}
              </ToggleButton>
            )}
          </NavLink>
        );
      })}
    </ToggleButtonGroup>
  );
}

Anyway, I do not wish to waste your time, I know there are more important issues and feature requests out there :)
Thanks for replying with actual code and examples!

@github-actions github-actions bot added status: waiting for maintainer These issues haven't been looked at yet by a maintainer and removed status: waiting for author Issue with insufficient information labels Jan 3, 2025
@github-actions github-actions bot reopened this Jan 3, 2025
@siriwatknp
Copy link
Member

@itayperry Based on your snippet, you can apply styles based on data attributes with sx prop. This way you can control how the selected should look like with a small change:

const childRoutes = [
  {
    name: "INBOX",
    to: "./inbox",
  },
  {
    name: "DRAFTS",
    to: "./drafts",
  },
  {
    name: "TRASH",
    to: "./trash",
  },
] as const;

function MyTabsToggler() {
  return (
    <Tabs color="primary" aria-label="basic tabs example">
      {childRoutes.map((subRoute) => {
        return (
          <NavLink to={subRoute.to} style={{ all: "unset" }} key={subRoute.to}>
            {({ isActive, isPending }) => (
              <Tab
                value={subRoute.name}
                aria-label={subRoute.name}
                data-selected={isActive ? "" : undefined}
                disabled={isPending}
                sx={{
                  '&[data-selected]': { background: 'primary.main', color: 'white' },
                }}
              />
            )}
          </NavLink>
        );
      })}
    </Tabs>
  );
}

Copy link

github-actions bot commented Jan 3, 2025

This issue has been closed. If you have a similar problem but not exactly the same, please open a new issue.
Now, if you have additional information related to this issue or things that could help future readers, feel free to leave a comment.

Note

@itayperry How did we do? Your experience with our support team matters to us. If you have a moment, please share your thoughts in this short Support Satisfaction survey.

@github-actions github-actions bot removed the status: waiting for maintainer These issues haven't been looked at yet by a maintainer label Jan 3, 2025
@itayperry
Copy link
Author

Hi there @siriwatknp,
This is a cool solution and I didn't think about it, but still it breaks the default MUI design/behavior, so it does not achieve its goal.

I still suggest changing the API to have self-awareness for the <Tab/> itself, like <ToggleButton/> is aware of its selection in the group.
This will enable new abilities far beyond comfortable routing... I think you should consider this.

@aarongarciah
Copy link
Member

@siriwatknp your solution requires users to recreate the selected built-in styles from Tab, which is not ideal.

@itayperry although a selected prop could be added to the Tab component, the tricky thing to consider here is only one tab can be selected at a time; that's why the Tabs component controls which tab is selected via the value prop. Introducing the selected prop would make impossible states possible, which is something we want to avoid. Feel free to propose alternative APIs or provide examples in other libraries that are closer to what you're looking for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component: tabs This is the name of the generic UI component, not the React module!
Projects
None yet
Development

No branches or pull requests

3 participants