I'm using react-router with code-splitting. Dynamic routes like AuthenticatedRoute
don't seem to work well with it.
If the user goes to the About
route, logs in and gets back to the About
route (without refreshing the page), nothing will be shown because the About
route code-splitting chunk doesn't get replaced/updated and it doesn't have the About
component imported.
The code:
Routes
import React from 'react';
import { Route } from 'react-router-dom'
import asyncComponent from "./AsyncComponent";
import AuthenticatedRoute from "./AuthenticatedRoute";
const AsyncHome = asyncComponent(() => import("../../containers/Home/Home"));
const AsyncAbout = asyncComponent(() => import("../../containers/About/About"));
const AsyncLogin = asyncComponent(() => import("../../containers/Login/Login"));
const Routes = () => (
<main>
<Route exact path="/" component={AsyncHome} />
<AuthenticatedRoute exact path="/about" component={AsyncAbout} />
<Route exact path="/login" component={AsyncLogin} />
</main>
)
export default Routes
AuthenticatedRoute
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Route, Redirect } from 'react-router-dom';
class AuthenticatedRoute extends Component {
render() {
const { props } = this;
const { component: C, user, ...newProps } = props;
const renderComponent = (routeProps) => {
return user ? <C {...routeProps} /> : <Redirect to="/login" />;
}
return <Route {...newProps} render={renderComponent} />
}
}
const mapStateToProps = state => ({
user: state.auth.user
})
const mapDispatchToProps = dispatch => bindActionCreators({
}, dispatch)
export default connect(
mapStateToProps,
mapDispatchToProps,
)(AuthenticatedRoute)
The problem seems to be related with the generation of chunks. If the About
route chunk is created without the user logged in, the chunk will not have the About
component there. If I refresh the page after logging in, the About
route chunk has the About
component there and all works fine.
I think when the user is not logged in it does not render your component because it goes in else part of this if statement. It will never route to about page unless user is logged in.