Reputation: 4235
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 thisvalue
("0") is not part of the document layout. Make sure the tab item is present in the document or that it's notdisplay: none
.
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.
Upvotes: 0
Views: 2931
Reputation: 20626
One thing missing in your code is the fact that you are always setting your value as 0 initially. Whereas it should be dependent on the page you are at
Modify your NavTabs component like this:
const router = useRouter();
const [value, setValue] = useState(pages.indexOf(router.route));
router
will give you the route and you can use it. The above example is basic and does not account for cases when pages does not include your route.
Upvotes: 2