Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 941
Tarun Khare Avatar asked Nov 30 '25 22:11

Tarun Khare


1 Answers

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.

like image 127
Andrew Hill Avatar answered Dec 02 '25 10:12

Andrew Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!