Simple React Overlay Spinner and Spinner with React-Redux
In this article we will look at the two simple ways of adding a full-screen overlay spinner to react web application using react-loading-overlay. First we will add the spinner and enable/disable it with a local react hook in a single component. Later we will add the activation of the spinner using react-redux state management.
npm i react-loading-overlay
Once the package is installed successfully, open App.js file in your project, remove unwanted default code and import LoadingOverlay. Your code should look as below:
It is as simple as this to setup the spinner up and running on your web application. You can check the documentation to customize the overlay and spinner. Next we will look at the two ways of configuring the overlay.
- Using simple react hook: We will create a hook “isActive” of type bool using “useState” in App.js file. Assign this hook to the “active” property of the LoadingOverlay component and then enable overlay spinner on a button click and after 2 seconds disable it back.
2. Using React-Redux: Configuring overlay spinner with react-redux will allow us to overlay the spinner anywhere in our application. Whether it is an API call or loading a resource, we can take the advantage of a generic overlay spinner.
npm i redux react-redux
Create a new file store.js in the project src folder and add the following code: (To make it simple: Action, Reducer and Store are added into one file)
Import Provider and store in index.js file and wrap the App component with Provider:
Finally, Connect the App component to store using react-redux connect in App.js file and instead of using local hook, pass the props property “isActive” to LoadingOverlay component:
Source code can be found here