React - Sticky Footer issue: Footer at bottom of App component; App component not at bottom of Body

时间:2018-03-25 18:56:30

标签: html css reactjs footer sticky-footer

I'm having some trouble with a sticky footer in react. I implemented the flexbox solution I saw on CSS Tricks, but the problem is The footer is at the bottom of the main App component, but the App component is not at the bottom of the body. Here's a picture that illustrates this problem:

enter image description here

Some code: In the render function of my App component I'm returning this:

render() {
  return (
    <div className="App">
      <div className="all-but-footer">
        <Header />
          <main className="content">
            <Switch>
              <Redirect from="/" to="/bio" exact />
              <Route path="/bio" exact component={Bio} />
            </Switch>

            <Route path="/videos" exact component={Videos} />
            <Route path="/gallery" exact component={Gallery} />
            <Route path="/magnet-podcast" exact component={MagnetPodcast} />
          <Route path="/contact" exact component={Contact} />
        </main>
      </div>

    <Footer />
  </div>

And of course I'm hooking into the root div with:

document.addEventListener('DOMContentLoaded', () => {

  const root = document.getElementById('root');

  ReactDOM.render(
    <Root />, root);
  registerServiceWorker();
});

With the root div in my index.html like so:

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <title>Louis Kornfeld</title>
  </head>
  <body>

    <div id="root"></div>

  </body>
</html>

In my CSS I tried giving the App a height of 100% and even tried giving the root div in the index.html a height of 100%. The body's only child is the root div, and the root div's child is App, so I figured giving these all height of 100% would stretch the components but nothing has worked.

Any ideas with how I can resolve this problem?

1 个答案:

答案 0 :(得分:2)

Normally, when you return an element from a component’s render method, it’s mounted into the DOM as a child of the nearest parent node

If you want to to insert a child into a different location in the DOM , You can make use React Portals

The one which worked for me is react-portal you can install it as a project dependency npm install --save react-portal

And inside your component you can :

    import { Portal } from 'react-portal';

    <Portal>
      This text is portaled at the end of document.body!
    </Portal>

    <Portal node={document && document.getElementById('youCanSelectAnyIdFromTheDOM')}>

    This text is portaled into San Francisco!
   </Portal>

You can read more about react-portal Here

相关问题