简体   繁体   中英

How do I create a multiple page app with a login component in react?

Recently I've tried building a web platform trough React. Everything's fine, everything's work ecc. But I've run in many problems when I tried to create a different page for the user login:

  1. I already had Routes in my code, so when I tried to add other Routes to another js file they simply didn't work.

  2. I have no clue how to do the authentication in react router, I've tried in many ways, followed many tutorials but nothing worked out.

<Switch>
    <Route exact path='/' component={Feed}/>
    <Route path="/user" component={Profilo}/>
    <Route path='/explore-page' component={ExplorePage} />
    <Route path='/events-page' component={EventsPage} />
    <Route path='/calendar-page' component={CalendarPage} />
    <Route path='/stats-page' component={StatsPage} />
    <Route path='/form' component={FormPage}/>
    <Route path="/user" component={Profilo}/>
    <Route path="/user/:userId" component={Profilo} />
</Switch>

This is all the routes I'm currently using inside a div to get the react component rendered. As I said before adding other routes in an upper file wouldn't give me a response.

So, in the end, I'm gonna ask you where should I put the route for the login and the home? In there or I should just moving everything?

Thank you in advance.

One simple way is adding the logic to handle authentication in your render function.

If the user is not authenticated. Redirect to the login page. Otherwise, go to your component

render() {
    if (!this.props.isAuth) {
        return (
            <Switch>
                <Route exact path="/" component={Login} />
                <Redirect to="/" />
            </Switch>
        );
    }
    return (<Switch>
        <Route
            // your router
        />
    </Switch>);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM