How to Add Activity Indicator in React Native WebView to Show Progress

WebView is an integral component in React Native. You can use it as a mobile browser inside your React Native app. As we know, web pages take some time to load. It’s better to show an ActivityIndicator when the web pages load every time.

First of all, install WebView on your project using any of the following commands.

yarn add react-native-webview

or

npm install --save react-native-webview

The iOS users should run the following command in the ios folder.

pod install

That’s the installation part.

You can show ActivityIndicator while loading by using two props of WebView- onLoadStart and onLoad. I show ActivityIndicator when the loading starts and hide the same when the loading ends. Look at the full example given below:

import React, {useState} from 'react';
import {View, ActivityIndicator} from 'react-native';
import WebView from 'react-native-webview';

const App = () => {
  const [visible, setVisible] = useState(true);

  const hideSpinner = () => {
    setVisible(false);
  };
  const showSpinner = () => {
    setVisible(true);
  };

  return (
    <View style={{flex: 1}}>
      <WebView
        onLoadStart={() => showSpinner()}
        onLoad={() => hideSpinner()}
        style={{flex: 1}}
        source={{uri: 'https://google.com'}}
      />
      {visible && (
        <ActivityIndicator
          style={{
            flex: 1,
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
            position: 'absolute',
            alignItems: 'center',
            justifyContent: 'center',
          }}
          size="large"
        />
      )}
    </View>
  );
};

export default App;

The following will be the output.

React Native WebView with Activity Indicator

That’s how you add webview with an activity indicator in react native.

1 thought on “How to Add Activity Indicator in React Native WebView to Show Progress”

Leave a Reply

%d bloggers like this: