• Stars
    star
    192
  • Rank 197,750 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple component that alerts when the user is inactive (i.e. when the App surface hasn't been touched for X ms)

react-native-user-inactivity

Version Documentation Maintenance License: MIT

Functional React Native component that notifies when the user stops interacting with the mobile screen for a given amount of time.

As of version 1.1.0, react-native-user-inactivity resets the timer also when the keyboard appears or disappears. If you want to avoid this behaviour, you can set the skipKeyboard property to true.

As of version 1.0.0, react-native-user-inactivity has been rebuilt as a functional component that uses the new React Hook API. Thanks to usetimeout-react-hook, react-native-user-inactivity supports timers different than the standard one (setTimeout). This has solved some of the most recurrent issues, such as #12, #16, #17.

Install

npm install react-native-user-inactivity

If you are running a version of react < 17 you'll need to include the --legacy-peer-deps flag.

npm install react-native-user-inactivity --legacy-peer-deps

๐Ÿ”‘ Key features

  • ๐Ÿฅ‡ supports generic timers (you're no longer constrained to setTimeout)
  • โš ๏ธ optional reset capability of the timer
  • โœจ super elastic behaviour thanks to the Hooks API
  • ๐Ÿ’ช written in TypeScript
  • โœ”๏ธ the core logic of this component is delegated to usetimeout-react-hook, which has 100% code coverage

โ” How to use

This package primarily exposes a single functional component, UserInactivity. The signature of the UserInactivity React props is the following:

interface UserInactivityProps<T = unknown> {
  /**
   * Number of milliseconds after which the view is considered inactive.
   * If it changed, the timer restarts and the view is considered active until
   * the new timer expires.
   * It defaults to 1000.
   */
  timeForInactivity?: number;

  /**
   * If it's explicitly set to `true` after the component has already been initialized,
   * the timer restarts and the view is considered active until the new timer expires.
   * It defaults to true.
   */
  isActive?: boolean;

  /**
   * Generic usetimeout-react-hook's TimeoutHandler implementation.
   * It defaults to the standard setTimeout/clearTimeout implementation.
   * See https://github.com/jkomyno/usetimeout-react-hook/#-how-to-use.
   */
  timeoutHandler?: TimeoutHandler<T>;

  /**
   * Children components to embed inside UserInactivity's View.
   * If any children component is pressed, `onAction` is called after
   * `timeForInactivity` milliseconds.
   */
  children: React.ReactNode;

  /**
   * If set to true, the timer is not reset when the keyboard appears
   * or disappears.
   */
  skipKeyboard?: boolean;

  /**
   * Optional custom style for UserInactivity's View.
   * It defaults to { flex: 1 }.
   */
  style?: StyleProp<ViewStyle>;

  /**
   * Callback triggered anytime UserInactivity's View isn't touched for more than
   * `timeForInactivity` seconds.
   * It's `active` argument is true if and only if the View wasn't touched for more
   * than `timeForInactivity` milliseconds.
   */
  onAction: (active: boolean) => void;
}

When a native timer is needed (in order to avoid issues such as #12, #16, #17) an implementation of usetimeout-react-hook's TimeoutHandler should be passed to the timeoutHandler prop. A default one (BackgroundTimer) is optionally provided: in order to use it you must:

  • manually run: npm i -S react-native-background-timer
  • manually link the native library: react-native link react-native-background-timer

In case of doubts, please refer to the official react-native-background-timer repository.

The default BackgroundTimer can be used like this:

import UserInactivity from 'react-native-user-inactivity';
import BackgroundTimer from 'react-native-user-inactivity/lib/BackgroundTimer';

export default () => {
  return (
    <UserInactivity
      timeForInactivity={2000}
      timeoutHandler={BackgroundTimer}
      onAction={isActive => { console.log(isActive); }}
      style={{ flex: 1, paddingTop: '10%' }}
    >
  );
}

Warning: it seems that react-native-background-timer doesn't work properly with Android 10+ (#41). I'm currently unable to reproduce the problem, but help from the open-source community on this matter is certainly appreciated.

โœจ Typings

Since the component itself is written in TypeScript, your editor's intellisense system should automagically detect the typings file (even if you're using plain JS!), thus providing a better developer experience. In fact, autocomplete capabilities and warning should come for free as you're typing the props to pass to the UserInactivity component.

๐Ÿ’ช Practical Example

import React, { useState } from 'react';
import { View, Text, TextInput, Button } from 'react-native';
import UserInactivity from 'react-native-user-inactivity';

export default () => {
  const [active, setActive] = useState(true);
  const [timer, setTimer] = useState(2000);

  return (
    <View style={{ flex: 1 }}>
      <UserInactivity
        isActive={active}
        timeForInactivity={timer}
        onAction={isActive => { setActive(isActive); }}
        style={{ flex: 1, paddingTop: '10%' }}
      >
        <Button id="btn-1" title="1 Press this to simulate activity" />
        <Button id="btn-2" title="2 Press this to simulate activity" />
        <Text id="text-1" style={{ textAlign: 'center' }}>Type below to simulate activity</Text>
        <TextInput
          id="text-input-1"
          style={{height: 40, borderColor: 'gray', borderWidth: 1}}
          onChange={() => { setActive(true); }}
          textContentType="creditCardNumber"
          value={timer.toString(10)}
          onChangeText={text => setTimer(Number.parseInt(text || 0, 10))}
        />
      </UserInactivity>
      <View style={{ flex: 3, backgroundColor: '#fcfcaa', }}>
        <Text style={{ textAlign: 'center' }}>{active ? 'ACTIVE' : 'NOT ACTIVE'}</Text>
        <Button title="Manually set to Active" onPress={() => { setActive(true); }} />
      </View>
    </View>
  );
}

Also, please checkout the example on Snack/Expo.


๐Ÿš€ Build package

This package is built using TypeScript, so the source needs to be converted in JavaScript before being usable by the users. This can be achieved using TypeScript directly:

npm run build

๐Ÿ‘ค Author

Alberto Schiabel

๐Ÿค Contributing

Contributions, issues and feature requests are welcome!
Feel free to check issues page. The code is short, throughly commented and well tested, so you should feel quite comfortable working on it. If you have any doubt or suggestion, please open an issue.

โš ๏ธ Issues

Chances are the problem you have bumped into have already been discussed and solved in the past. Please take a look at the issues (both the closed ones and the comments to the open ones) before opening a new issue. Unfortunately, at the moment I'm not able to offer fast support, because I am a student worker and React Native is no longer part of my main tech stack.

๐Ÿฆ„ Show your support

Give a โญ๏ธ if this project helped or inspired you! In the future, I might consider offering premium support to Github Sponsors.

๐Ÿ“ License

Built with โค๏ธ by Alberto Schiabel.
This project is MIT licensed.

Related packages

More Repositories

1

usetimeout-react-hook

React.js custom hook that sets a leak-safe timeout and returns a function to cancel it before the timeout expires
TypeScript
37
star
2

pnpm-monorepo-example

Opinionated Node.js monorepo example with pnpm, turborepo, and jest
JavaScript
24
star
3

pate

Modern and light-fast CLI app that scans all the desired files of a certain folder and returns a list with the name of the files which contain a certain RegEx pattern
TypeScript
24
star
4

priority-queue

Header-only, generic and dependency-free C++17 implementation of Heaps and Priority Queues
C++
15
star
5

palitra

Utility that finds the N most frequent colors in a picture, approximated to CSS3 color names
Go
15
star
6

workshop-rust-wasm

Code for my workshop "Production-ready WebAssembly with Rust" presented at RustLab 2023 in Florence
Rust
14
star
7

fetch-timeout

HTTP/S fetch wrapper that adds the possibility to set a timeout after which a custom error is returned.
JavaScript
14
star
8

eurorust-2022

Accompanying code for my talk "No free lunch: Limits of Wasm as a bridge from Rust to JS" presented @ EuroRust2022 in Berlin
Rust
11
star
9

nanoid

Golang port of ai/nanoid (originally written in JavaScript)
Go
10
star
10

react-native-universal-picker

Cross platform component that uses React Native's Picker on Android and ActionSheetIOS on iOS.
JavaScript
10
star
11

react-native-animated-hide-view

A performant-wise and configurable react-native component that can toggle the opacity of its children, with or without animation. :octocat:
JavaScript
9
star
12

jkds

A set of utilities and data structures written in C++20
C++
9
star
13

amplrestapi

Asynchorous AMPL REST Interface written in Python 3.6
Python
7
star
14

fastify-zod-validate

Fastify route handler validation plugin using Zod in TypeScript
TypeScript
7
star
15

xtremejs-2022

Accompanying code for my talk "Write a Scraper as a State Machine with Playwright and Kafka" presented @ XtremeJS 2022
TypeScript
6
star
16

eurorust-2023

Accompanying code for my talk "Underrated Gems of Rust & WebAssembly: Errors, Async, I/O" presented @ EuroRust2023 in Brussel
TypeScript
5
star
17

whileplus

Interpreter for the While+ educational programming language for the Software Verification course at UNIPD.
Haskell
4
star
18

react-native-maps-example

Since the official react native example provided by React Native didn't work on Android, I fixed it and published it here.
JavaScript
4
star
19

react-native-animated-checkbox

Minimalistic and customizable <CheckBox /> component for React Native. โœ…
JavaScript
4
star
20

bioalgo-QCluster-vs-isONclust

Final project for the Algorithms for Bioinformatics class at UNIPD
Jupyter Notebook
4
star
21

cnn-of-density-maps-for-crowd-counting

White paper about the Crowd Counting problem co-written for the Computer Vision class at UNIPD
3
star
22

grazjs-2023

Accompanying code for my talk "Type-safe bindings for Node.js with Rust and WebAssembly" presented @ Graz.js 2023
JavaScript
3
star
23

remix-vite-cloudflare-pages

Example usage of Remix (with Vite) + Cloudflare Pages + Prisma
TypeScript
2
star
24

react-native-horizontal-progress-bar

Simple React Native animated horizontal progress bar.
JavaScript
2
star
25

budgeted-maximum-coverage-rust-vs-scala

Scala
2
star
26

node-lib-boilerplate

Minimal boilerplate aimed to speed up the process of creating a new NodeJS library
JavaScript
2
star
27

bachelors-thesis

Bachelor's Thesis: Development of a Redis management platform with serverless microservices on AWS
2
star
28

docker-ampl-python

Docker image with AMPL and Python 3.6
Dockerfile
2
star
29

kalk

Final project developed for the Object Oriented Programming Course at the University of Padova
C++
2
star
30

node-congress-2023

Accompanying code for my talk "Type-safe bindings for Node.js with Rust and WebAssembly" presented @ Node Congress 2023 in Berlin
JavaScript
2
star
31

rust-capnp-wasm

Accompanying code for my talk "Towards Zero-Copy Binary (De)Serialisation: TypeScript <-> Rust" presented @ Trivago Rust Guild Meetup 2023 in Dรผsseldorf
TypeScript
2
star
32

audiovol

Toggle and get the system's volume. Compatible with Mac OS and Linux
JavaScript
1
star
33

capnp-ts

Cap'n Proto serialization/RPC system for TypeScript & JavaScript
TypeScript
1
star
34

socrates-austria-2023

Accompanying code for my talk "WebAssembly for backend devs" presented @ SoCraTes Austria 2023 in Linz
JavaScript
1
star
35

algorithms-hw3

TeX
1
star
36

lattice-submodular-maximization

Python
1
star
37

reprod-8832

Reproduction of https://github.com/prisma/prisma/issues/8832
TypeScript
1
star
38

certifications

This is where I keep my public certifications
1
star
39

reprod-14539

TypeScript
1
star
40

DoubleLinkedList

Object Oriented Programming assignment @ University of Padova, Italy.
C++
1
star
41

algorithms-hw2

Exact and approximate Metric TSP implementation in C++17
C++
1
star
42

fixed-math

Converts a decimal number using fixed-point notation, avoiding the conversion from number to string of Number.toFixed.
TypeScript
1
star
43

json2kv

Dependencyless JS library that converts a generic JSON-like object to a map-like, key-value object.
JavaScript
1
star
44

redux-error-snapshot-immutable

Redux thunk and Immutable utility that aims to ease the process of retrying last failed action
JavaScript
1
star
45

rn-swipeable

JavaScript
1
star
46

BST---4.4

C++
1
star
47

automata-project

C++
1
star
48

react-native-linked-project

Project hosted with the sole purpose of providing a react-native project with the libraries I use most already linked on iOS (and soon on Android too)
Objective-C
1
star
49

react-native-boilerplate

Personal react-native boilerplate that implements redux, reselect, immutable, react-navigation
JavaScript
1
star
50

react-matrix-text

ReactJS component that splits and renders a text in a given number of columns
TypeScript
1
star
51

redux-error-snapshot

Redux thunk utility that aims to ease the process of retrying last failed action
JavaScript
1
star
52

FlipCounter

JavaScript
1
star
53

palitrux-ui

TypeScript
1
star
54

docker-gulpease

Docker-ready Python utility for evaluating the Gulpease Index of one or more PDF documents.
Python
1
star
55

linspace-generator

Generator of a linearly spaced vector of numbers, inspired by MATLAB.
TypeScript
1
star
56

react-native-advanced-geolocation-example

React Native example focused on Android permissions and autotoggling of GPS
Objective-C
1
star
57

palitrux

Go
1
star
58

combinatorial-optimization-tsp

Final project for the "Methods and Models for Combinatorial Optimization" class at UNIPD.
Jupyter Notebook
1
star
59

sentiment-go

Golang version of the npm package sentiment
Go
1
star
60

wmic-1.3.15

Slightly modified wmic and linux amd64 compiled executable
C
1
star
61

prisma-test-multischema-sql-server

Test multiSchema preview feature before releasing [email protected]
TypeScript
1
star
62

palitra-lambda

AWS Lambda function that finds the N most frequent colors in a picture
Go
1
star
63

rust-guild-trivago-2023

Accompanying code for my talk "WebAssembly in Production: from Rust to TypeScript and back" presented remotely @ Rust Guild Trivago 2023
JavaScript
1
star
64

kongres-nextjs-2024

Accompanying code for my talk "Interactive web apps at the Edge with Remix, Neon, and Prisma" presented @ Kongres Next.js 2024 in Warsaw
TypeScript
1
star
65

is-equally-spaced

Utility function that given an array of numbers, evaluates wether or not every element is equally spaced
TypeScript
1
star
66

size-in-bytes

Simple NodeJS function that returns the number of bytes expressed from a string
JavaScript
1
star