LoginSignup
2
1

【ReactNative】WebViewの基本的な機能とAPIの活用方法

Last updated at Posted at 2024-02-23

はじめに

ReactNativeでWebViewを扱う場面があったので、公式ドキュメントを参考に簡単な機能を理解していきます。以下の公式のAPI Referenceを参考に進めていきます。

React Native WebView API Reference

内容

今回はこちらのライブラリーを使用します。

インポート

import { WebView } from "react-native-webview";

useRefを用いる

WebViewのAPIのメソッドを用いるためには、useRefを使用する必要があります。使用することによって、WebViewのAPIのメソッドの参照が可能となります。

const MyWebView = () => {
  const webViewRef = useRef(null);

  return (
    <View>
      <WebView
        ref={webViewRef}
        source={{ uri: "https://www.google.com/" }}
      />
    </View>
  );
};
  • WebViewコンポーネントには、refプロパティにwebViewRefを設定しています。これにより、webViewRefWebViewコンポーネントにアクセスすることができます
  • sourceプロパティにはWebViewが表示するページのURIが指定されています。今回の例ではGoogleのウェブページを表示しています

WebViewコンポーネントの内部の値を参照することにより、以下URLの公式ドキュメントのAPIを用いることができます。

WebViewのAPIを用いた実装例

今回のWebViewの挙動を制御する実装コードの例として、

画面を一つ戻る

webViewRef.current.goBack();

画面の再読み込み

 webViewRef.current.reload();

指定のURLへの遷移

webViewRef.current.injectJavaScript(
    `window.location.href = 'http://〇〇';`
);

などが挙げられます。他にもメソッドが用意されており、ドキュメントを参考に実装するとより柔軟な実装が可能です。

サンプルコード

上記を考慮した全体のコードを以下に記します。

App.js
import React, { useRef } from "react";
import { View, StyleSheet, Button } from "react-native";
import { WebView } from "react-native-webview";

const MyWebView = () => {
  const webViewRef = useRef(null);

  const handleGoBack = () => {
    if (webViewRef.current) {
      webViewRef.current.goBack();
    }
  };

  const handleReload = () => {
    if (webViewRef.current) {
      webViewRef.current.reload();
    }
  };

  const handleGoToSpecificUrl = () => {
    if (webViewRef.current) {
      webViewRef.current.injectJavaScript(
        `window.location.href = 'https://www.anime-chiikawa.jp/';`
      );
    }
  };

  return (
    <View style={styles.container}>
      <WebView
        ref={webViewRef}
        source={{ uri: "https://www.google.com/" }}
        style={styles.webview}
      />
      <View style={styles.buttonContainer}>
        <Button title="戻る" onPress={handleGoBack} />
        <Button title="リロード" onPress={handleReload} />
        <Button title="特定のリンクへ遷移" onPress={handleGoToSpecificUrl} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 40,
    marginBottom: 40,
  },
  webview: {
    flex: 1,
  },
  buttonContainer: {
    flexDirection: "row",
    justifyContent: "space-around",
    alignItems: "center",
    padding: 10,
  },
});

export default MyWebView;

挙動確認

iOSシミュレーター

Simulator Screen Recording - iPhone 15 - 2024-02-21 at 09.23.44.gif

正しい挙動を確認しました👏ちいかわかわいい

最後に

他にも良い方法があれば、コメントいただけると大変うれしいです。
良かったと思ったら、いいねやTwitterのフォローよろしくお願いいたします!

個人でアプリを作成しているので、良かったら覗いてみてください!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1