4

This is a basic situation: I have a Nav with links and several routes for those links in a main content area.

const App = () => (
    <div id="page-container">
        <Nav />
        <main id="main">
            <Switch>
                <Route exact path="/" component={IndexPage} />
                <Route exact path="/blog" component={BlogPage} />
                <Route exact path="/about" component={AboutPage} />
                <Route component={NotFoundPage} />
            </Switch>
        </main>
    </div>
);

Sometimes when I click the nav links the main content area updates instantaneously, and sometimes it takes maybe 2 or 3 seconds to load the next component. I believe that's an outrageous amount of time to wait (with no indication that anything is loading).

All I seemed to find was React Router Transitions, which I tried, but it seemed like it required a static timeout for the transition animation. I only want a loading animation to appear where necessary; I do not want the routes animated every single time. React Transition Group also seems to require each route to be wrapped in a Transition component, which requires a location argument, which I don't seem able to have in my current layout.

Here's what I hoped to do:

I hoped to add a boolean state variable to my Page component to keep track of loading:

class Page extends React.Component {
    constructor (props) {
        super(props);
        this.state = {
            loading: true
        };
    }
    componentDidMount() {
        this.setState({
            loading: false
        });
    }

    render() {
        return (
            <article className={this.state.loading ? 'loading' : ''}>
                ... stuff ...
            </article>
        );
    }
}

But this doesn't seem to work, because componentDidMount fires after render, i.e. after all of the loading time. So, basically, (1) it loads for awhile, (2) renders article with the 'loading' class for probably a few milliseconds until (3) componentDidMount sets the state and renders again, replacing the class.

So I'm guessing I need to add the loading animation on the previous page component, instead of the next page component? Or is it better to ajax all my page content? I'm really surprised how little information I've found on this, and I'm hoping someone has some helpful advice. Thanks!

bozdoz
  • 10,929
  • 7
  • 55
  • 86
  • Possible duplicate of [display a simple loading between routes in react router](https://stackoverflow.com/questions/47104208/display-a-simple-loading-between-routes-in-react-router) – Mehmet Bora Ezer Sep 25 '18 at 08:37

0 Answers0