Search code examples
reactjsmaterial-uidashboardtoolpad

How do I navigate to another page using the value of a Material UI Select component inside a Dashboard Layout?


I'm using the Dashboard Layout component of Material UI's Toolpad Core. It works well. It shows all the icons on the slideout and correctly navigates to the page when clicked. It uses BrowserRouter in the main page (app/(dashboard)/layout.tsx).

One of those pages contains a MUI Select component. I want to navigate to one of another set of sub-pages from there, depending on what is selected. Unfortunately, That doesn't work. Nothing happens.

I don't want to add the sub-pages to the main navigation because it makes too many icons. I know I could fold them in under a sub-navigation of one of the items, but I'd rather not. It gets too long and busy. I prefer the Select component. But if I add another router on that page, the compiler complains that there can be only one router in the application. I can't figure away around that restriction.

Here's some code to clarify.

app>(dashboard)>layout.tsx

const NAVIGATION: Navigation = [{
    segment: 'diet',
    title: 'Diet',
    icon: <DietIcon />,
  },
 {
    segment: 'exercise',
    title: 'Exercise',
    icon: <ExerciseIcon />,
  },
...}]

diet is the page that contains the Select component.

export default function RootLayout(props: any) {
  return (
    <html>
      <body>
        <BrowserRouter>
        <AppProvider
          navigation={NAVIGATION}
        >
          {props.children}
        </AppProvider>
        </BrowserRouter>

      </body>
    </html>
  );
}

Clicking on the Diet icon takes you to

app>(dashboard)>diet/page.tsx

export default function DietPage() {
    const [page, setPage] = React.useState('');
    const navigate = useNavigate();
    const handleChange = (event: SelectChangeEvent) => {
    const selectedPage = event.target.value;
    console.log("selectedPage=", selectedPage)
    navigate(`./${selectedPage}`); // Navigate to the selected page
    setPage(event.target.value as string);
  };

  return (
    <table>
      <tbody><tr>
        <td><h2>Diet</h2></td>
        <td>
          <FormControl sx={{ m: 1, minWidth: 120 }}>
            <InputLabel>Select Food Category</InputLabel>
            <Select
              value={page}
              labelId="demo-simple-select-label"
              id="demo-simple-select"
              label="Select Food Category"
              sx={{ width: 200 }}
              onChange={handleChange}
            >
              <MenuItem value={"meals"}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <MealIcon fontSize="small" />
                  &nbsp;&nbsp;
                  <div>Meals</div>
                </div>
              </MenuItem>
              <MenuItem value={"calendar"}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <CalendarIcon fontSize="small" />
                  &nbsp;&nbsp;
                  <div>Calendar</div>
                </div>
              </MenuItem>
            </Select>
          </FormControl>
        </td>
      </tr></tbody>
    </table>

When you select Meals from the dropdown, it's supposed to navigate to meals.tsx, but it doesn't.

app>(dashboard)>diet>meals.tsx

export default function MealsPage() {
    return (
      <h2>
        Meals Page
      </h2>
    );
  }

clicking meals does nothing

I also tried first answer suggestion so that now the BrowserRouter looks like

<BrowserRouter>
  <AppProvider
    navigation={NAVIGATION}
    branding={BRANDING}
    theme={theme}
  >
    {props.children}
  </AppProvider>
  <Routes>
    <Route path="diet" element={< DietPage />} />
    <Route path="meals" element={<MealsPage />} />
  </Routes>
</BrowserRouter>

But it still does nothing.

I think the problem has something to do with the next.js framework as asserted in next.js router issue but I can't get that to work either.


Solution

  • I don't know particular versions of MUI library and react router (v6?). But based on what I see you might have misconfigured your router configuration. You must've had routes section for the Browser router:

    <BrowserRouter>
        <Routes>
            <Route path="diet" element={< DietPage />} />
            <Route path="meals" element={<MealsPage />} />
        </Routes>
        ...
    </BrowserRouter>
    

    NAVIGATION object doesn't provide router configuration. It provides elements for the left navigation menu.

    Also MUI version should be compatible with react router version, because different versions might have different ways to specify routes.

    Keep in mind that the current MUI website example is using v7 router as it's base.

    Edit:

    You need to create router somewhere (call createBrowserRouter for v7) and provide this info to MUI.

    This might be done with AppProvider router prop:

    <AppProvider
      navigation={NAVIGATION}
      router={router}
    >
    ...
    </AppProvider>
    

    Or by utilizing ReactRouterAppProvider for seamless integration with react router:

    
    export default function App() {
      return (
        <ReactRouterAppProvider navigation={NAVIGATION} branding={BRANDING}>
          <Outlet />
        </ReactRouterAppProvider>
      );
    }
    
    ...
    
    export default function Layout() {
      return (
        <DashboardLayout>
          <PageContainer>
            <Outlet />
          </PageContainer>
        </DashboardLayout>
      );
    }
    
    ...
    
    const router = createBrowserRouter([
      {
        Component: App, // root layout route
        children: [
          {
            path: "/",
            Component: Layout,
            children: [
              {
                path: "diet",
                children: [
                  {
                    path: "",
                    Component: DietPage,
                  },
                  {
                    path: "meals",
                    Component: MealsPage,
                  },
                  {
                    path: "calendar",
                    Component: CalendarPage,
                  },
                ],
              },
              {
                path: "exercise",
                Component: ExercisePage,
              },
            ],
          },
        ],
      },
    ]);
    
    ReactDOM.createRoot(document.getElementById("root")!).render(
      <React.StrictMode>
        <RouterProvider router={router} />
      </React.StrictMode>
    );
    

    Here's codesandbox with working example:

    https://codesandbox.io/p/sandbox/stupefied-lamport-d4stcf