• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

209
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>
    );
  }
}
almost 3 years 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;
  }
almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda