Search code examples
reactjsreact-nativeauthenticationreact-navigationreact-native-fbsdk

React Native - Login with React Navigation


I'm struggling a bit with login functionality in my react native app. I'm using the facebook-login, and it is working. But what to do after successful login, is where I'm struggling.

I've tried this: To have two navigators in App.js. One for the login, and one for all the rest. In the app.js, I have a loggedIn-state which is false by default. Then when the login is successful, I want to change the loggedIn-state to true, and swap to the other navigator. But I'm unable to sending a prop from the LoginStack-navigator, to the App.js-component, so I'm not able to change the state in App.js

This is the code I'm having now:

// App.js
const RootStack = createStackNavigator({
  Single: Single,
  Search: Search,
  Home: Homepage,
  TagsSingle: TagsSingle
},
{
  initialRouteName: 'Home',
  drawerBackgroundColor: '#2D2D2D'
});

const LoginStack = createStackNavigator({
  Login: Login,
},
{
  drawerBackgroundColor: '#2D2D2D',
});

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loggedIn: false
    }
  }
  handleLogin = () => {
    console.log("Test");
    this.setState({loggedIn: true});
  }
  render() {
    return (
      <View style={{flex:1}}>{this.state.loggedIn ? <RootStack /> : <LoginStack handleLogin={this.handleLogin} />}</View>
    );
  }
}

// Login.js - where the login happens
class Login extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      message: 'Logg inn med facebook'
    }
  }
  _fbLogin = (ev) => {
    LoginManager.logInWithReadPermissions(['public_profile']).then(function(result){
      if(result.isCancelled){
        console.log('Login cancelled');
      }
      else{
        console.log('Login succes ' + result.grantedPermissions);
        ev.setState({message: 'Logget inn'});
        ev.props.handleLogin();                // creates error
      }
    }, function(error){
      console.log("An error occured:");
      console.log(error);
    });
  }
  render() {
    return (
      <View style={{ flex:1, backgroundColor: '#2D2D2D', justifyContent: 'center', alignItems: 'center' }}>
        <View>
          <TouchableOpacity onPress={() => {this._fbLogin(this)}}>
            <Text style={{color:'#fff'}}>{this.state.message}</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}
export default Login;

But nothing happens in the HandleLogin-function in App.js, and I'm getting an error saying 'ev.props.handleLogin is not a function' (I've also tried calling the prop without '()', which gives no error, but still no reaction).

How can I solve this? Also, am I on the right track here, with the two navigators?


Solution

  • Try this example from their documentation.