'React NextJS page navigation with tabs - display not updating correctly

I'm attempting to navigate between pages using tabs:

import * as React from 'react'
import Box from '@mui/material/Box'
import Tabs from '@mui/material/Tabs'
import Tab from '@mui/material/Tab'
import {useState, useEffect} from 'react'
import { useRouter } from 'next/router'

const LinkTab = (props) => 
{
  const router = useRouter()

  const handleTabChange = (e) =>
  {
    e.preventDefault()
    router.push(e.target.href)
  }

  return (
    <Tab
      component = 'a'
      onClick = {e => handleTabChange(e)}
      {...props} />
  )
}

const NavTabs = () => 
{
  const pages = ['/', '/two', '/three']
  const [value, setValue]  =  useState(0)

  const handleChange  =  (e, v)  => 
  {
    setValue(v)
  }

  return (
    <Box sx = {{width: '100%'}}>
      <Tabs value = {value} onChange = {(e, v) => handleChange(e, v)} centered>
        <LinkTab label = 'Page One' href = {pages[0]} />
        <LinkTab label = 'Page Two' href = {pages[1]} />
        <LinkTab label = 'Page Three' href = {pages[2]} />
      </Tabs>
    </Box>
  );
}

export default NavTabs

This works in terms of navigation - clicking a tab takes you to the expected page.

But the selected tab doesn't update correctly on the actual display.

Related error message (doesn't cause a crash but shows in console):

next-dev.js?3515:32 MUI: The value provided to the Tabs component is invalid. The Tab with this value ("0") is not part of the document layout. Make sure the tab item is present in the document or that it's not display: none.

enter image description here

When the site first loads, Page One is the home page and is also correctly shown as selected. If I click on Page Two I navigate there right away, but I have to click on it again to actually have the tab display update to show that page as selected. And then if I click on Page Three, I'll again navigate there correctly, but the display will go back to showing Page One as selected.

I think this has something to do with when/where I call e.preventDefault() and the fact that state is being initiated with 0 for the first page. But I'm new to React, so I'm not exactly sure what I've done wrong.

The code above is modified from the MUI example found here. Implementing the example code exactly as is correctly updates the display, but doesn't actually navigate, so I had to make some changes to use the router.

The NavTabs component is part of an AppBar component.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source