Skip to content

Next Navigation Menu Expansion on Route Change Not Working #5125

@mogrady88

Description

@mogrady88

Im having some difficulty with my left navigation menu expanding on route changes when I implement a search. My search is simply running from an input with a handleSearch function that calls router.push/router.refresh:

import { useRouter } from 'next/navigation';
const router = useRouter();

// handleSearch
  router.push(url);
  router.refresh();

Im also using the NextAppProvider. My implementation is here:

'use client';

import { NextAppProvider } from '@toolpad/core/nextjs';
import { usePathname } from 'next/navigation';
import { useMemo, useRef } from 'react';
import type { ReactNode } from 'react';

import uiNav from './(components)/nav';
import foundationsNav from './(foundations)/nav';
import overviewNav from './(overview)/nav';
import supportNav from './(support)/nav';

const BRANDING = {
  logo: '',
  title: 'Thing',
};

// This fixes nav menu expansion on page load. Search is different
// Issue was incorrect state for navigation. It was out of sync with the routes.
// Now we store navigation references to prevent recreation
const navMap = {
  components: uiNav,
  foundations: foundationsNav,
  overview: overviewNav,
  support: supportNav,
};

export function ToolpadWrapper({ children, theme }: { children: ReactNode; theme: any }) {
  const fullPath = usePathname();
  const prevSegmentRef = useRef<string>('');

  // Only recalculate navigation when the segment actually changes
  const navigation = useMemo(() => {
    const firstSeg = fullPath.split('/')[1];
    const segment = firstSeg.includes('docs-2') ? fullPath.split('/')[2] : firstSeg;

    // If we're still in the same section, return the same navigation reference
    if (segment === prevSegmentRef.current) {
      return navMap[segment as keyof typeof navMap] || [];
    }

    prevSegmentRef.current = segment;
    return navMap[segment as keyof typeof navMap] || [];
  }, [fullPath]);

  return (
    <NextAppProvider branding={BRANDING} navigation={navigation} theme={theme}>
      {children}
    </NextAppProvider>
  );
}

From what I can see in the src code for NextAppProviderApp the internal router should pick up my router.url/router.push calls right? I dont get any expansion when I call these. Am I missing something?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions