Implement idle timeout popup in React

Today we will show you how to implement idle timeout popup in React application.

You may need to develop/integrate the functionality to detect inactive users to auto logout in React. So in this article, we will look the small React Example to handle the auto logout. In other words, we can say session-based timeout example in react.js.

Demo Application

Output - Implement idle timeout popup in React - Clue Mediator
Output – Implement idle timeout popup in React – Clue Mediator

Steps to implement idle timeout popup in React

  1. Create a react app and install npm dependencies
  2. Prepare components for demo
  3. Write a logic to set idle timeout popup
  4. Output

1. Create a react app and install npm dependencies

Let’s create a react app using the create-react-app npm package. Run the following command to create a react app.

For the demo, we will create components (Login & Dashboard) and handle the redirection using routing.

The complete guide of Routing in React.

Here, we will use the following two libraries for this project.

Run the following command to install the above two libraries.

2. Prepare components for demo

Now, we will simply create two different components such as Dashboard & Login. By clicking on the Login button, we will redirect to the Dashboard page and use the Logout button to return to the Login page.

index.js
App.js
Login.js
Dashboard.js

3. Write a logic to set idle timeout popup

Let’s write a logic to implement idle timeout functionality using react-idle-timer and show the modal popup when the user goes idle.

In this example, we will display a popup after 10 seconds of idle time. After displaying the popup, you will be redirected to the login page in 5 seconds. By clicking on the Stay Logged In button, we will restart the idle timer and stay on the same page.

Without wasting time, let’s create a modal popup component called TimeoutModal.

TimeoutModal.js

In the above component, we are passing the following three attributes.

  • showModal – Flag to show/hide the modal popup.
  • togglePopup – Method to manage the visibility of the modal popup.
  • handleStayLoggedIn – Stay logged in and reset the idle timer.

Let’s import the react-idle-timer & TimeoutModal in the Dashboard to handle the idle timeout popup.

Dashboard.js

Let’s configure the following properties for the IdleTimer.

  • stopOnIdle – Set to true, so we can stop the timer when the user goes idle.
  • onIdle – Method to capture an event when the user is idle.
  • timeout – Idle timeout in milliseconds.

4. Output

Run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *