Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

58
Vistas
Restrict app from going back via react-native-webview (React Native)

I have developed a website using react and now I've been trying to use this via webview in react native.

Problem: When I am using back button, the app exits.

Reason:

  • In my React Website I am using Link {from react-router dom} so the navigation is not being added in history.
  • In React Native since onNavigationStateChange uses history, navState.canGoBack() is returning false.

What can I include in this else block in handleBackButton so that app doesn't exit?

import React, { Component } from "react";
import { SafeAreaView, Platform, StatusBar } from "react-native";
import { BackHandler } from "react-native";
import { WebView } from "react-native-webview";

export default class Marketplace extends Component {
  constructor(props) {
    super(props);
    this.state = {
      canGoBack: false,
    }
  }

  WEBVIEW_REF = React.createRef();

  componentDidMount() {
    BackHandler.addEventListener("hardwareBackPress", this.handleBackButton);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.handleBackButton);
  }

  handleBackButton = () => {
    if (this.state.canGoBack) {
      this.WEBVIEW_REF.current.goBack();
      return true;
    } else {
      console.log("Else block");
      // what to add here to restrict the app to exit
    }
  };

  onNavigationStateChange = (navState) => {
    console.log("navState", navState.canGoBack);
    this.setState({
      canGoBack: navState.canGoBack,
    });
  };

  render() {
    return (
      <SafeAreaView
        style={{
          flex: 1,
          paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
        }}
      >
        <WebView
          source={{
            uri: "http://localhost:3000/",
          }}
          ref={this.WEBVIEW_REF}
          onNavigationStateChange={this.onNavigationStateChange}
        />
      </SafeAreaView>
    );
  }
}
7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

if you want to restrict the user from exiting the app then you'll have to return true in else statement as well or you can do simply do this:-

  handleBackButton = () => {
    if (this.state.canGoBack) {
      this.WEBVIEW_REF.current.goBack();  
    }
    return true;
  }
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos