Pass parameter from one Page to another React Native

Asked

Viewed 310 times

-1

I have a login page and another with a webview, I am not able to pass a parameter of the login page to another page with the webview.

App.js

import React from "react";
import Routes from "./Routes";

export default function App() {
  return <Routes />;
}

Routes.js

import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";

import Login from "./pages/Login";
import WebViewSite from "./pages/WebViewSite";

const AppStack = createStackNavigator();

export default function Routes() {
  return (
    <NavigationContainer>
      <AppStack.Navigator>
        <AppStack.Screen name="Login" component={Login} />
        <AppStack.Screen name="WebViewSite" component={WebViewSite} />
      </AppStack.Navigator>
    </NavigationContainer>
  );
}

Login/index.js This sends the parameter

import React, { useState, useEffect } from 'react';
import {
    KeyboardAvoidingView,
    View,
    Text,
    Image,
    TextInput,
    TouchableOpacity,
    StatusBar,
    Animated,
    Keyboard,
    Alert
} from 'react-native';
import { useNavigation } from "@react-navigation/native";

import styles from './styles';
import logo from '../../assets/Logo.png';
import config from '../../config';
import api from '../../services/api';
//import servicos from '../../services/services';

export default function Login() {
    const [usuario, setUsuario] = useState('');
    const [senha, setSenha] = useState('');

    const navigation = useNavigation();

    function navigateToWebViewPar(url) {
        navigation.navigate('WebViewSite', { link: 'https://github.com/' });
    }


    function Login() {
        api.get('/disponibilidade/status_clienteapp')
            .then(function (res) {
                if (res.status == 200) {
                    RetornaLink()
                } else {

                }
                //console.log(response.status);
            })
            .catch(function (error) {
                console.log(error);
            });
    }


    function RetornaLink() {
        if (!usuario) {
            Alert.alert('Atenção', 'Informe o Usuário!')
        } else {
            if (!senha) {
                Alert.alert('Atenção', 'Informe a Senha!')
            } else {
                api.get('/login/verifica_cadastro/'.concat("", usuario).concat("/", senha).concat("/", config.codEmpresa))
                    .then(function (response) {
                        var ret = response.data;
                        console.log(ret);
                        if (ret == 30) {
                            alert('Campo Usuario ou Senha Inválido.');
                        } else if (ret == 40) {
                            alert('Serviço Temporariamente Indisponível.');
                        } else if (ret == 50) {
                            alert('Erro Inesperado! Por favor tente novamente.');
                        } else {
                            navigateToWebViewPar(ret);
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    })
            }
        }

    }


    return (
        <>
            <View style={styles.container}>
                <StatusBar backgroundColor="#d1dae1" />

                <View style={styles.containerLogo}>
                    <Image source={logo} style={styles.logo}></Image>
                    <View style={styles.AlinharOpcoes}>
                        <Text style={styles.nomeDaEmpresa}>{config.nomeEmpresa}</Text>
                        <Text style={styles.txtApp}>APP</Text>
                    </View>
                </View>

                <Text style={styles.txtInfo}>Faça login para iniciar sua sessão</Text>

                <TextInput
                    style={styles.input}
                    placeholder="Usuário"
                    keyboardType="numeric"
                    textContentType="none"
                    autoCapitalize="none"
                    // autoCompleteType="email"
                    autoCorrect={false}
                    onChangeText={(usuario) => setUsuario(usuario)}
                />

                <TextInput
                    style={styles.input}
                    placeholder="Senha"
                    //keyboardType="visible-password"
                    textContentType="password"
                    autoCapitalize="none"
                    autoCompleteType="password"
                    autoCorrect={false}
                    secureTextEntry={true}
                    onChangeText={(senha) => setSenha(senha)}
                />

                <TouchableOpacity style={styles.buttonSubmit} onPress={Login}>
                    <Text style={styles.submitText}>Acessar</Text>
                </TouchableOpacity>

                <View style={styles.AlinharOpcoes}>
                    <TouchableOpacity style={styles.buttonRegister}>
                        <Text style={styles.registerText}>Solicitar Acesso</Text>
                    </TouchableOpacity>

                    <TouchableOpacity style={styles.buttonResetPass}>
                        <Text style={styles.ResetPassText}>Esqueci Minha Senha</Text>
                    </TouchableOpacity>
                </View>

                <Text style={styles.txRodape}>Desenvolvido por DinTec Sistemas</Text>

            </View>
        </>
    );
};

Webviewsite/index.js This should receive the parameter

import React from "react";
import { useNavigation,  } from "@react-navigation/native";
import { WebView } from 'react-native-webview';

export default class WebViewSite extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        name: this.props.navigation.getParam('link')   
    };
  }

  render() {
      return (
      <WebView source={{ uri: 'https://reactnavigation.org/docs/params/' }} style={{ marginTop: 20 }} />
      );    
  }
}

I tested in several ways and keeps giving error

Typeerror: Undefined is not an Object (evaluating '_Native.useNavigation.params.name')

and also

Typeerror: _this.props.navigation.getParam is not a Function. (In '_this.props.navigation.getParam('link')', '_this.props.navigation.getParam' is Undefined)

I don’t know what else to do, I went through all the documentation but I couldn’t solve.

1 answer

0

According to the documentation itself, you are doing everything right when submitting the parameter, the error is time for you to catch it. In the documentation, when passing a parameter, you should catch it with "route.params", in the props. So your code should look like this:

import React from "react";
import { useNavigation,  } from "@react-navigation/native";
import { WebView } from 'react-native-webview';

export default class WebViewSite extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        name: this.props.route.params.link  
    };
  }

  render() {
      return (
      <WebView source={{ uri: 'https://reactnavigation.org/docs/params/' }} style={{ marginTop: 20 }} />
      );    
  }
}

If in doubt, see the documentation of React Navigation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.