Hello Everyone, In this article, I am going to explain to you how can you add a loader with your APIs calls in React Application, I am using a third-party npm package, which will help to show the loading spinner at DOM, Here’s how you can set up a loader in your React application
Install an NPM Package: I am going to use react-loader-spinner package, it will help us to show a loading screen on DOM. First, install the package on your existing React application
find your package here – https://www.npmjs.com/package/react-loader-spinner
npm install react-loader-spinner --save
BashCreate a Loader Component: First, we need to create a component for your loader. This component will display the loading indicator. it has content of the npm package setup. In the component where you’re performing asynchronous operations, import and conditionally render the loader component.
import React, { useRef } from 'react'
import LoadingBar from 'react-top-loading-bar'
export const SampleAPICallComponent = () => {
const ref = useRef(null)
// this is for a example for api call handler with loader
const fetchDataFromAPI = () => {
// Start Loader Here
ref.current.continuousStart()
fetch("https://reqres.in/api/users?page=2").then(res => {
// Stop Loading
ref.current.complete()
// your response come here
});
}
return (
<div>
<LoadingBar color='#f11946' ref={ref} />
<button onClick={fetchDataFromAPI}>Complete</button>
<br />
</div>
)
}
LoaderComponent.jsImport Your Loader Component to Parent Component: you can import your loader component to any component to start and stop the loading screen.
import './App.css';
import {SampleAPICallComponent} from './Loader'
function App() {
return (
<div className="App">
<SampleAPICallComponent ></SampleAPICallComponent>
</div>
);
}
export default App;
JavaScriptIn this example, the Loading Progressbar will be displayed while the data is being fetched, and it will be replaced with the actual content once the data has been fetched and loaded. This pattern provides a smooth user experience by indicating that something is happening in the background.
Happy Coding โบ๏ธ
OpenLayers Show and Hide Layers: https://stacktrick.com/show-hide-layers-in-openlayers/
No Comments
Leave a comment Cancel