3

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.

1
  • 1
    Try to add style to your NavBar component. It needs to be display: "flex"; flex: 1; Commented Jan 5, 2020 at 14:04

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, it is because you may have used fixed-top class if using bootstrap or other similar css property. I was also having same issue for below code, after removing fixed-top class its working fine now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.