Page doesn't load when typing url of a private component into browser's adress bar (React-router v4)

195 views Asked by At

I'm making an app with authentication, using react-router and react-router-redux for handling routing. My routes get rendered as expected when I start from a non-private route, hovewer when I type a private route's url directly into the browser's adress bar nothing gets loaded(screenshot). How can I fix this problem?

PrivateRoute.js

const PrivateRoute = ({userStatus, component: Component, ...rest }) => {

    const stuffToShow = (props) => {
        if(userStatus.authenticated) {
            return <Component {...props}/>;
        }
        return <Redirect to={{
            pathname: '/login',
            state: { from: props.location }
        }}/>
    };

    return <Route exact {...rest} render={stuffToShow}/>

};

export default connectComponent(['userStatus'], PrivateRoute);

routes.js

export function renderRoutes(routes) {
    return routes.map((route, i) => {
        if(route.private) {
            return <PrivateRoute key={i} {...route} />;
        }
        return <Route key={i} {...route}/>;
    })
}

const routes = [
    {
        path: '/',
        exact:true,
        component: Home
    },
    {
        path: '/login',
        exact:true,
        component: Login
    },
    {
        path: '/registration',
        exact:true,
        component: Registration
    },
    {
        path: '/users/:id',
        exact:true,
        component: UserPage,
        private: true
    }, 
    {
        path: '/users',
        exact:true,
        component: Users,
        private: true
    },
    {
        path: '/goodBye',
        exact:true,
        component: Goodbye
    },
    {
        path: '*',
        component: NoMatch
    }
];

root:

    <Provider store={store}>
        <Router history={history}>
            <div>
               <Header />
                <Switch>
                    {renderRoutes(routes)}
                </Switch> 
            </div>
        </Router>
    </Provider>

How I render html on express server:

        this.app.use('/api/users', userRoute);
        this.app.use('/api/blogPosts', blogPostsRoute);
        this.app.use('*',(req,res) => res.sendFile(path.resolve(__dirname, '..', 'public', 'index.html')));

enter image description here

1

There are 1 answers

5
Win On

Try to modify this part:

const stuffToShow = (props) => {
    if(userStatus.authenticated) {
        return <Component {...props}/>;
    }
    return (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    );
};

The <Redirect /> is multiple lines, should be enclosed with (). That's my best guess of your problem.