2

I am using Next.js and I want to know how to change the url on the same page without refresh it. I am using shallow=true but it still render to the next page.

This is my code:

<Tabs>
   <Tab href='test/1' label='Sample Exam'/>
   <Tab href='test/1/exam' label='Test Exam'/>
</Tabs>
<TabPanel value={tabvalue} index={0}>
   <SampleComponent />
</TabPanel> 
<TabPanel value={tabvalue} index={1}>
   <TestComponent />
</TabPanel> 

This is the logic but does not work

    const [tabValue, setTabValue] = React.useState(0);
    const router = useRouter();
    const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
        setTabValue(newValue);
        useEffect(() => {
            router.replace('/test/1', '/test/1/exam', { shallow: true});
        }, []);
    };

I have already test router.push it does not work and windows replace state is a bad idea. The tabs will look like this.

     Sample Exam          |        Test Exam

if you click sample exam it will show the Sample Details same with the Test but it must be on the same page.

Thanks.

William
  • 89
  • 1
  • 14

1 Answers1

0

Old post, but someone may find it useful:

The problem is, that you can not shallow route '/test/1' to '/test/1/exam', because nextjs uses file system based routing. Inside your pages directory, 'test/1' will point to test/1/index.js or if you are using dynamic paths it is test/[id].js. However '/test/1/exam' will point to test/1/exam/index.js or, in case of dynamic paths, it can be test/[id]/exam/index.js. These two files are not on a different level, thus shallow routing won't work.

You can try add a query, e.g.: test/1?show=exam, because that can be handled with only 1 file: test/[id].js. Shallow routing will work this way.

Other way is is to display something in case of the sample exam, too. e.g. instead of using 'test/1' it could be 'test/1/sample' and 'test/1/exam' will remain. In this case, a single file will be able to handle the two separate options with shallow routing: test/[id]/[slug].js

See more: https://nextjs.org/docs/routing/introduction AND https://nextjs.org/docs/routing/dynamic-routes

metaaa
  • 11
  • 3