mardi 18 septembre 2018

React router auth pattern

I am trying to implement the authentication using React + Firebase. I want to achieve a simple result. When user is not logged in, he sees "Welcome" on the Welcome component by "/" path. When user is logged in, he sees "Welcome, username". I implemented Login as a controlled component which has some fields(name, email) and signIn method. Same with Signup component. I cannot figure out how to better implement Welcome component which can receive props. I tried to pass in the props to Welcome component, but then it has form and this cannot be passed into component prop of Route, thus i have an error. I also saw the solution with protected paths, but i don't need exactly protected paths from not authenticated users. I just want to pass user data from Login(firebase.auth().currentUser) to Welcome component. Could you please suggest better, modern or elegant way to implement such flow?

import React, {Component} from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import Welcome from './Welcome';
import Login from './Login';
import Signup from './Signup';

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={Welcome} />
          <Route path="/login" component={Login} />
          <Route path="/register" component={Signup} />
        </Switch>
      </BrowserRouter>
    );
  }
}

export default App;

Aucun commentaire:

Enregistrer un commentaire