Implementation

Let’s see how we can implement the idle timeout feature in the React application with the react-idle-timer library. As a first step, we need to install react-idle-timer dependencies in the existing application.

npm i react-idle-timer --save

Once installed we have to import these modules in the Layout.js file.

Layout.js

Since LayOut is the main component once logged in from the Login, we need to implement this logic in it. We are setting the Idle time 5 seconds which means we will get a warning message after 5 seconds of inactivity and timeout as 5 seconds which means it will be timed out within another 5 seconds.

I set both idle time and timeout time to 5 seconds for the demonstration purpose. Usually, these times are longer in the actual environments, typically it is around 15 mins.

Layout.js with idle-timer implementation

I want to show a modal window whenever the user is idle and give some options for the user to logout or stay as shown in the figure.

modal window

For this, we are using a react-bootstrap modal component. We need to create a separate component and import that component in the Layout.js as shown below.

This is a stateless component which takes props and returns modal window based on the properties provided to this component. Notice that we are importing required components Modal and Button from react-bootstrap.

IdleModal.js

Once created, we need to import this file in the Layout.js and pass the required props.

Idle timeout Modal part of Layout.js

Along with this, we don’t want the idle timeout feature on the login screen. For this, I created Layout.js which has all the routes besides login. Here is the App component which loads the Layout component for the route /dashboard and the Layout component loads the actual DashboardPage component.

App and Login components

Here is the complete Layout.js file. If you notice the function _onIdle() at line 40. We are logging out the user if he is idle even after showing the modal window. We can accomplish this in a number of ways but I used isTimedOut the property in the state. When the user is idle for the first time, I am showing the modal window and setting this flag as true in the state and reset the timer. If the user is still idle, I am logging the user out based on the flag isTimedOut

If the user responds to that modal window, we are using handleLogout and handleClose functions to take the appropriate action at lines 53 and 57 respectively.

complete Layout.js

Summary