Search code examples
javascriptandroidreactjsreact-nativereact-native-webview

Cannot read property '#<WebView>' of undefined react native


I'm creating a Webview in react-native but when I navigate to any page and try to navigate back app gets close.

I have read some answers on STACK-OVERFLOW and tried some code to handle the back button of android, But it didn't help.

Here is the code which tried:

import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  BackHandler,
} from 'react-native';

import WebView from 'react-native-webview';

const App: () => React$Node = () => {

  const [canBack, setCanBack] = useState(false);
  useEffect(() => {
    this.backHandler = BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
    console.log('mounted')

    return () => {
      this.backHandler.remove()
      console.log('unmounted')
    }

  }, [canBack]);

  handleBackPress = () => {
    console.log('back btn pressed')
    console.log('canBack is '+canBack)
    if(canBack) {
      this.refs[myWebView].goBack();
      return true;
    }
  }


  onNavigationChange = (navState) => {
    console.log(navState);
    // console.log(navState.canGoBack)
    setCanBack(currentCanBack => navState.canGoBack);
    console.log(canBack);
  };

  return (
      <SafeAreaView style={{ flex: 1,}}>
        <StatusBar barStyle="dark-content" />
        <WebView
          ref={(c) => {this.myWebView = c} }
          source={{ uri: 'https://infinite.red' }}
          domStorageEnabled={true}
          onNavigationStateChange={(navState) => this.onNavigationChange(navState)}
        />
      </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  scrollView: {
    flex: 1,
    backgroundColor: 'lightgrey',
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default App;

In this when I press back button It is giving me error "Cannot read property '#' of undefined react native"


Solution

  • Here I got the solution of this problem.

    I just used this.myWebView.goBack(); and it worked. So, may be in react 0.61 when we are using hooks and we are in function component we should use it this way.