In a ReactJS application using React Router, transitioning between routes often involves loading data or components asynchronously. During this transition period, it’s essential to provide visual feedback to users to indicate that something is happening. It is a good practice to display a loading screen while you prepare your page to display. It is very easy to display a simple loading indicator between routes in react-router.
In this article, we’ll explore how to display a simple loading indicator between routes using React Router.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Create Home.js and App.js as shown in the above image.
Implementation: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from "react" ; import { BrowserRouter as Router, Route } from "react-router-dom" ; import { useState } from "react" ; import Home from './components/Home' ; function App() { return ( // Create route for each page, since we // have only one page. So we are defining // only one route. <Router> <Route path= "/" exact component={Home} /> </Router> ); } export default App; |
Home.js
Javascript
import React from "react" ; import { useEffect, useState } from "react" ; const Home = () => { // Set loading state to true initially const [loading, setLoading] = useState( true ); useEffect(() => { // Loading function to load data or // fake it using setTimeout; const loadData = async () => { // Wait for two second await new Promise((r) => setTimeout(r, 2000)); // Toggle loading state setLoading((loading) => !loading); }; loadData(); }, []) // If page is in loading state, display // loading message. Modify it as per your // requirement. if (loading) { return <div>Loading....</div> } // If page is not in loading state, display page. else { return <h1>Home</h1> } } export default Home; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: