Home > OS >  How can i access my WebView from another component?
How can i access my WebView from another component?

Time:08-26

I have a basic WebView:

const WebViewComponent = () => {
  function sendDataToWebView() {
     webviewRef.current.postMessage('Hello world');
 }

  const webviewRef = useRef();
    return (
      <SafeAreaView>
        <WebView  
          ref={webviewRef}
          source={{
            uri: 'https://www.google.com/',
          }}
        />
      </SafeAreaView>
    );
  }

Calling sendDataToWebView() works in this component since i have the reference. (useRef()).

But in another component:

const anotherComponent = () => {
      const webviewRef = useRef();
      webviewRef.current.postMessage('Hello world');
      
}

webviewRef is undefined.

How can i access my WebView from another component?

CodePudding user response:

you can't just create a new ref and use that in your anotherComponent. If you want to display the webview in your anotherComponent, you need to import it and return is as part of the anotherComponent.

CodePudding user response:

There are 2 ways to do this, with and without using name ref for the reference property.

  1. Without using ref prop name, i.e. use any other name.
const WebViewComponent = ({ webviewRef }) => {
  return (
    <WebView
      ref={webviewRef}
      source={{ uri: 'https://www.google.com/' }}
    />
  );
};
const AnotherComponent = () => {
  const webviewRef = useRef();

  useEffect(() => {
    const test = () => {
      const run = "window.alert('haha');";
      webviewRef.current?.injectJavaScript(run);
    };
    setTimeout(test, 3000);
  }, []);

  return (
    <SafeAreaView>
      <WebViewComponent
        webviewRef={webviewRef}
        // ....
      />
    </SafeAreaView>
  );
}
  1. Using ref. This is possible using forwardRef feature of React. You can read more about it here.
const WebViewComponent = React.forwardRef((props, ref) => {
  return (
    <WebView
      ref={ref}
      source={{ uri: 'https://www.google.com/' }}
    />
  );
});
const AnotherComponent = () => {
  const webviewRef = useRef();

  // .....

  return (
    <SafeAreaView>
      <WebViewComponent
        ref={webviewRef}
        // ....
      />
    </SafeAreaView>
  );
}
  • Related