Can't pass data input to a textfield from one screen to the other. React-native

133 Views Asked by At

This is my Home screen

        class HomeScreen extends React.Component {
        constructor(props) {
        super(props);
        this.state = {username: null, password: null, isPasswordHidden: true, toggleText: 'Show'};
      }

      handleToggle = () => {
        const { isPasswordHidden } = this.state;

        if (isPasswordHidden) {
          this.setState({isPasswordHidden: false});
          this.setState({toggleText: 'Hide'});
        } else {
          this.setState({isPasswordHidden: true});
          this.setState({toggleText: 'Show'});
        }
      }

      //Validate() to check whether the input username is in Mail format
      validate = (inputValue) => {
        let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ; // Regex for Emails
        // let reg = /^(\+\d{1,3}[- ]?)?\d{10}$/; // Regex for phone numbers
        return reg.test(inputValue);
      }
      clearText(fieldName) {
        this.refs[fieldName].clear(0);
      }

      render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}></Text>


            <TextInput
              ref={'input1'}
              style={styles.input}
              placeholder="Username"
              onChangeText={value => this.setState({username: value})}

            />

            <TextInput
              ref={'input2'}
              style={styles.input}
              placeholder="Password"
              maxLength={10}
              secureTextEntry={this.state.isPasswordHidden}
              onChangeText={value => this.setState({password: value})}

            />

            <TouchableOpacity
              onPress={this.handleToggle}
            >
              <Text>{this.state.toggleText}</Text>

            </TouchableOpacity>

            <View style={{padding: 20}}>
              <TouchableOpacity onPress={() => {

                if (!this.validate(this.state.username)) {
                  Alert.alert("Invalid");
                  Keyboard.dismiss();
                } else if (this.state.username === '[email protected]' && this.state.password === 'password') {

Here I have passed the parameters to the next screen where I want to display the values that I have input the textInput field. But it is not displaying in the next screen. I don't know why. It was working fine when I added a normal stack navigator without any drawer navigation and all.

                  this.props.navigation.navigate('Welcome', {
                    u_name: this.state.username,
                    p_word: this.state.password,
                  });
                  Keyboard.dismiss();
                  this.clearText('input1');
                  this.clearText('input2');
                } else if (this.state.username === null && this.state.password === null) {
                  Alert.alert("Invalid");
                } else {
                  Alert.alert("Login Failed");
                  this.clearText('input1');
                  this.clearText('input2');
                  Keyboard.dismiss();
                }

              }}>
                <View style={styles.button}>
                  <Text style={styles.buttonText}>LOGIN</Text>
                </View>
              </TouchableOpacity>
            </View>

          </View>
        );
      }
    }

This is my Welcome screen

Here I have fetched the values from the previous screen and stored to a variable. Now it is printing USERNAME: name and PASSWORD: word

 class WelcomeScreen extends Component {
    render() {
    const { navigation } = this.props;
    const u_name = navigation.getParam('username', 'name');
    const p_word = navigation.getParam('password', 'word');
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>WELCOME</Text>
        <Text>USERNAME: {JSON.stringify(u_name)}</Text>
        <Text>PASSWORD: {JSON.stringify(p_word)}</Text>
      </View>
    );
  }
}

Navigators

const WelcomeTabNavigator = createBottomTabNavigator({
  Welcome: {screen: WelcomeScreen},
  Profile,
  Settings,
}, 
{
  navigationOptions:({navigation}) => {
    const {routeName} = navigation.state.routes[navigation.state.index];
    return {
      headerTitle: routeName
    };
  }
})

const WelcomeStackNavigator = createStackNavigator({
  WelcomeTabNavigator: WelcomeTabNavigator
},
{
  defaultNavigationOptions:({navigation}) => {
    return {
      headerLeft: (
        <Icon 
          style={{paddingLeft: 20}}
          onPress={() => navigation.openDrawer()}
          name="md-menu" 
          size={30}
        />
      )
    };
  }
})

const AppDrawerNavigator = createDrawerNavigator({
  Welcome: {screen: WelcomeStackNavigator}
},
{
  contentComponent:(props) => (
    <View style={{flex:1}}>
        <SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
            <DrawerItems {...props} />
            <Button 
              title="Logout" 
              onPress={() => {

                props.navigation.navigate('Home')
              }}
            />
        </SafeAreaView>
    </View>
  ),
  drawerOpenRoute: 'DrawerOpen',
  drawerCloseRoute: 'DrawerClose',
  drawerToggleRoute: 'DrawerToggle'
})

const AppSwitchNavigator = createSwitchNavigator({
  Home: {screen: HomeScreen},
  Welcome: {screen: AppDrawerNavigator}
});

const AppContainer = createAppContainer(AppSwitchNavigator);
2

There are 2 best solutions below

1
On

I think you should use u_name insted of username in getParam

Your code const u_name = navigation.getParam('username', 'name');

New code const u_name = navigation.getParam('u_name', 'name');

Same thing for password

Or you could use navigator method like this and not change getParam method

this.props.navigation.navigate('Welcome', { username: this.state.username, password: this.state.password, });

0
On

I got it. It's the issue with the navigator section. I changed this

   const AppSwitchNavigator = createSwitchNavigator({
  Home: {screen: HomeScreen},
  Welcome: {screen: AppDrawerNavigator}
});

to this

  const AppSwitchNavigator = createStackNavigator({
  Home: {screen: HomeScreen},
  Welcome: {screen: AppDrawerNavigator}
});

When you add switch navigator it resets the previous screen thereby losing the input value.