Picture Credits : https://goo.gl/e6M8RK

In this blog post I will demonstrate that how you can build a Loading Screen or a Loader in react. By following this method you will be able to call the loading screen from any component at any time. This trick comes very handy when we are working on large applications and we have to toggle the loading screen.

There are many ways to implement a dynamic loading screen but by using RxJS it becomes fun to implement such feature in your application. The biggest advantage we have with this approach that you can toggle the loading screen from any component or function that want to show the loading while doing some operations. Lets dive into the implementation.

I will be using codesandbox for this particular example.

If you want to setup locally try the following commands

npm install -g create-react-app

npx create-react-app my-app

cd my-app

npm start

For starting the project I will be creating the following structure.

Directory Struture

Install RxJs

npm install --save rxjs

Open Loader.jsx and copy the following code ( I will be linking the code at the end of the example )

In index.js where you will be adding the Loader component as it is the parent component of your app, So it’s recommended to put the loader in the root level component which is index.js in this regard

In utilities.js add the following code.

Now if everything is setup properly ( You can copy the whole code including the CSS files from the following link: React Loader Source Code)

You will see the following screen:

After clicking on the show loading button you will see the following loading screen for 3 seconds.

You can also do multiple things using this approach like handling Modal/Dialog or passing data as well.

Feel free to leave a comment below !