Search code examples
react-nativereact-native-router-flux

Wrong button displayed for 'undefined' in React-Native


I am using React Native and having difficulty recognizing "undefined" in my 'initial' screen, designated as "Home". Here is the code.

Routes.js

import React from 'react'
import { Router, Scene } from 'react-native-router-flux'
import Home from './Home.js'
import About from './About.js'
import Login from './Login.js'
import Other from './Other.js'

const Routes = () => (
   <Router>
      <Scene key = "root">
         <Scene key = "home" component = {Home} title = "Home" initial = {true} />
         <Scene key = "about" component = {About} title = "About" />
         <Scene key = "login" component = {Login} title = "Login" />
         <Scene key = "other" component = {Other} title = "Other" />
      </Scene>
   </Router>
)
export default Routes

Home.js

import React, { useState, useContext, createContext } from 'react'
import { Button, TouchableOpacity, Text } from 'react-native';
import { Actions } from 'react-native-router-flux';

import { LogContextProvider, LogContext } from './LogContext'

const Home = (props) => {
const status = useContext(LogContext);

   const goToAbout = () => {
      Actions.about()
   }
   const goToLogin = () => {
      Actions.login()
   }

      console.log('props called: ' + props.address);  //displays undefined
      console.log('props called: ' + props.name);  //displays undefined
      console.log('props called: ' + props.login);  //displays undefined


   return (
         <LogContext.Provider value={status}>
      <TouchableOpacity style = {{ margin: 128 }} onPress = {goToAbout}>
         <Text>This is HOME!</Text>
      </TouchableOpacity>
      {props.login === "undefined" ? (
        <Button
          title="Go to Login"
          onPress={goToLogin}
        />
      ) : (
        <Button
          title="Do Something"
          onPress={() => Actions.Other()}
        />
      )}
         </LogContext.Provider>
   )
}
export default Home

My code is written so that upon startup of the app, the 'props.login' is "undefined" (as confirmed by the 'console.log") however the proper button ("Go to Login") is NOT being displayed...why? Since the initial startup/run of the app does not pass any variables to 'props' I do not understand why the correct button is not exhibited. Any help appreciated.


Solution

  • From looking at your code I think the problem is that you check for the string "undefined" instead of just undefined. These are not equal so the "Go to Login" button won't be shown. So change that:

    // ...
    {
      props.login === undefined ? (
        <Button title="Go to Login" onPress={goToLogin} />
      ) : (
        <Button title="Do Something" onPress={() => Actions.Other()} />
      );
    }
    // ...