Search code examples
javascriptreactjsreact-routerreact-router-domframer-motion

Transition page content excluding the header and footer


I've been trying to add some nice transitions between the pages on my website using framer motion and react router.

This is my code:

        <AnimatePresence initial={false} exitBeforeEnter>
            <Switch location={location} key={location.pathname}>
                
                <Route path="/" exact>
                    <LandingPage />
                </Route>

                <PrimaryLayout>     
                    <Route path="/home">
                        <HomePage />
                    </Route>

                    <Route path="/about" >
                        <AboutUs />
                    </Route>

                    <Route path="/test" >
                        <TestPage />
                    </Route>
                </PrimaryLayout>

            </Switch>
        </AnimatePresence>

The "PrimaryLayout" is just a layout with a header, the landing page is the only page not using this layout.

The animation between the landing page and any other page works smoothly as the layout with the header fades in along with the page content but transitioning between pages that both use the layout is what I'm struggling with.

Whenever I switch between those pages the layout with the header animates out and then back in which looks weird.

Any help with this would be greatly appreciated.


Solution

  • Assuming your header and footer is the same for all the pages, you should move the header and footer out of your Page components, and out of the <AnimatePresence> component.

    <Header />
             <AnimatePresence initial={false} exitBeforeEnter>
                <Switch location={location} key={location.pathname}>
                    {/* Only the main content gets animated. No headers / footers in here. */}
                </Switch>
            </AnimatePresence>
    <Footer />