how to make sticky footer with react router

If you want your website to have a footer that sticks to the bottom of the page, even when there isn't enough content to fill the entire page, you can use CSS to make a sticky footer. Here's how to do it with React Router:

Create a new component for your footer. This can be a simple div element that contains your footer content:


import React from 'react';

function Footer() {
  return (
    <div className="footer">
      <p>This is the footer.</p>
    </div>
  );
}

export default Footer;

Add the following CSS to your stylesheet to make the footer sticky:


.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 60px; /* adjust height to match your footer content */
}

This will position the footer at the bottom of the page and make it stay there even if there isn't enough content to fill the page.

Finally, import your Footer component into your React Router file and place it inside your Router component:


import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Footer from './Footer';

function App() {
  return (
    <Router>
      <div className="App">
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/contact" component={Contact} />
        </Switch>
        <Footer />
      </div>
    </Router>
  );
}

export default App;

Make sure to place the Footer component outside the Switch component so that it appears on every page.

Alternative Method: Use Flexbox

If you prefer to use Flexbox instead of absolute positioning, you can use the following CSS:


.App {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.main {
  flex: 1;
}

.footer {
  flex-shrink: 0;
}

This will create a flex container that takes up the full height of the viewport, with the main content stretching to fill the available space and the footer sticking to the bottom.

Both methods are effective for creating a sticky footer in React Router. Choose the one that works best for your project!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe