Search code examples
javascriptcssreactjsreact-routerreact-spring

How to fix simultaneously loading two components bug?


I used react-router-dom and react-spring's useTransitions, animated for page transitions, but transition animation works well, but there are some bugs. I think I can solve it with CSS, but I do not know what to do. If you know how to solve it, I would be very thankful if you help me.

I tried page transitions using react-router-dom, react-spring, useTransitions, animated, __RouterContext

No error messages. it's some bugs

It rises from bottom to top. I just want to be in the center and give the opacity effect when moving the page.

function App() {
  const { location } = useContext(__RouterContext);
  const transitions = useTransition(location, location => location.pathname, {
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 }
  });
  return (
    <React.Fragment>
      <Navbar />
      {transitions.map(({ item, props, key }) => (
        <animated.div key={key} style={props}>
          <Switch location={item}>
            <Route exact path="/" component={Home} />
            <Route exact path="/profile" component={Profile} />
            <Route exact path="/about" component={About} />
            <Route exact path="/project" component={Project} />
            <Route exact path="/contact" component={Contact} />
          </Switch>
        </animated.div>
      ))}
    </React.Fragment>
  );
}

export default App;
enter image description here


Solution

  • It is hard to fix it without a working example. But if I understand right your problem is, that the new page appears under the old page. And it jumps up when the old page disappears. This is the way the transition is working. When you want that the leaving and entering transitions overlapping with each other you have to fix it with CSS as you already mentioned. Something like this:

    const transitions = useTransition(location, location => location.pathname, {
      from: { opacity: 0, position: 'absolute' },
      enter: { opacity: 1 },
      leave: { opacity: 0 }
    });
    

    This is a similar example: https://codesandbox.io/s/page-transition-with-react-router-and-react-spring-b07jp