简体   繁体   中英

ReactJS component going behind Navbar

In my React app, I have a navigation bar on top. I call this Navbar component in App.js as shown below.

export default function App() {
   return (
      <Router>
         <Fragment>
            <Navbar />
            <Route exact path="/" component={Home} />
            <section>
               <Switch>
                  <Route exact path="/login" component={Login} />
                  <PrivateRoute exact path="/dashboard" component={Dashboard} />
               </Switch>
            </section>
         </Fragment>
      </Router>
   );
}

The problem is that, whenever I hit any of these URLs like '/login', '/dashboard', The component associated with them renders behind the navbar and not below it. While I can add multiple <br/> tags below <Navbar /> to shift these components below, but this does not seem like a good solution as some components already have significant whitespace above them and adding <br/> will shift them even further below which I don't want. How to solve this issue? My other components return simple <div> . My Navbar is a <Appbar position='fixed'> from the material-ui/core library.

The official Material UI documentation covers this specific issue in detail: https://material-ui.com/components/app-bar/#fixed-placement

If you use Fixed Placement on a Material UI AppBar you will need to offset your content by either including a second empty <Toolbar /> component below the appbar or by using theme.mixins.toolbar CSS.


Solution A using a second <Toolbar /> component:

function App() {
  return (
    <React.Fragment>
      <AppBar position="fixed">
        <Toolbar>{/* content */}</Toolbar>
      </AppBar>
      <Toolbar />
    </React.Fragment>
  );
}

Solution B using theme.mixins.toolbar :

const useStyles = makeStyles(theme => ({
  offset: theme.mixins.toolbar,
}))

function App() {
  const classes = useStyles();
  return (
    <React.Fragment>
      <AppBar position="fixed">
        <Toolbar>{/* content */}</Toolbar>
      </AppBar>
      <div className={classes.offset} />
    </React.Fragment>
  )
};

MUI also suggests using position="sticky" instead to avoid this issue; however this is not supported in IE11 so use with caution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM