Add a loading animation in React using react-spinners
Today, we’ll show you how to add a loading animation in React using react-spinners. react-spinners
is a popular library for adding loading spinners in React applications. It provides a collection of pre-built spinner components that can be easily imported and used in your app.
This library is lightweight and easy to use and it allows you to pick a spinner that fits your needs. It provides a wide variety of spinner types such as CircleLoader, PacmanLoader, PulseLoader, etc. With react-spinners you can easily customize the spinner by using props like size, color, loading. It is compatible with both React and React Native.
Demo Application
Add a loading animation in React using react-spinners
1. Project structure
- react-loading-spinner-example
- node_modules
- public
- index.html
- src
- App.js
- index.css
- index.js
- package-lock.json
- package.json
- README.md
2. Package dependencies
Run the following command to install react-spinners npm package.
1 | npm i react-spinners |
You will find the version of the following packages in React application.
3. Implementation
Refer to the following files for implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import React, { useState } from 'react'; import { ClipLoader, BarLoader, PropagateLoader, RingLoader } from "react-spinners"; function App() { const [loading, setLoading] = useState(true); return ( <div className="App"> <h4>Add a loading animation in React using react-spinnerst - <a href="https://www.cluemediator.com">Clue Mediator</a></h4> <button onClick={() => setLoading(!loading)}>Toggle Loaders</button> <div className='spinners'> <ClipLoader color="blue" size={30} loading={loading} cssOverride={{ display: "block" }} /> <PropagateLoader loading={loading} /> <RingLoader loading={loading} /> <BarLoader loading={loading} color="purple" /> </div> <div className='note'> <b>Note:</b> It accepts basic colors: maroon, red, orange, yellow, olive, green, purple, white, fuchsia, lime, teal, aqua, blue, navy, black, gray, silver </div> </div> ); } export default App; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | body { margin: 20px; font-family: Arial, Helvetica, sans-serif; } .spinners { width: 540px; margin-top: 20px; display: flex; justify-content: space-between; align-items: center; } .note { margin-top: 20px; width: 540px; color: #444; } |
1 2 3 4 5 6 7 8 9 10 11 12 | import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <App /> </React.StrictMode> ); |
4. Output
Run your application and check the output in the browser.
Live Demo
That’s it for today.
Thank you for reading. Happy Coding..!!