Home > OS >  React. Link MUI without reloading page
React. Link MUI without reloading page

Time:09-11

Using component MUI Link, my page is reloaded. So I use the Link component from react-route-dom, but it turns out that <.a> is inside another and error on console enter image description here

If I remove MUI.Link, then navbar looks like bad

Code:

import {Link as LinkRouter} from "react-router-dom"
import Link from "@mui/material/Link";

export default function Navbar() {
    return (
        <>
            <GlobalStyles styles={{ul: {margin: 0, padding: 0, listStyle: 'none'}}}/>
            <AppBar
                position="sticky"
                color="default"
                elevation={0}
                sx={{borderBottom: (theme) => `1px solid ${theme.palette.divider}`}}
            >
                <Toolbar sx={{flexWrap: 'wrap'}}>
                    <Typography variant="h4" color="inherit" noWrap sx={{flexGrow: 1}}>
                        <LinkRouter to="/account/wall" className="site-title">YourQuestion</LinkRouter>
                    </Typography>
                    <nav>
                        <CustomLink to="/account/wall">Wall</CustomLink>
                        <CustomLink to="/account/message">Message</CustomLink>
                        <CustomLink to="/account/notice">Notice</CustomLink>
                        <CustomLink to="/account/friends">Friends</CustomLink>
                        <CustomLink to="/account/profile">Profile</CustomLink>
                    </nav>
                </Toolbar>
            </AppBar>
        </>
    )
}

function CustomLink({to, children, ...props}) {
    return (
        <>
            <Link
                variant="button"
                color="text.primary"
                sx={{ my: 1, mx: 1.5 }}
            >
                <LinkRouter to={to} {...props}>
                    {children}
                </LinkRouter>
            </Link>
        </>
    )
}

My github repository

CodePudding user response:

You can pass component="span" prop to MUI Link component like this:

<Link
    component="span"
    variant="button"
    color="text.primary"
    href="#"
    sx={{ my: 1, mx: 1.5 }}
>
    <LinkRouter to={to} {...props}>
      {children}
    </LinkRouter>
</Link>
  • Related