Home Detect outside press in React Native
Post
Cancel

Detect outside press in React Native

onPress and onClick events are one of the most common events used on mobile, web, and desktop apps development. But what if we want the opposite? We want to detect the press event outside of a component. Luckily this is a common pattern that there are modules that handle this.

airbnb/react-outside-click-handler have been great but it does not work with React Native only on React web.

This is why I developed react-native-outside-press, which works on most React Native platforms such as Vanilla, Expo, react-native-web, react-native-windows, and react-native-macos.

Step 1: Create a blank React Native project.

1
2
$ npx react-native init sample
$ cd sample

Skip this step when you already have a functioning app.

Step 2: Install the module.

1
$ yarn add react-native-outside-press

Step 3: Using the module.

Wrap your app with EventProvider.

1
2
3
4
5
6
7
8
9
import { EventProvider } from 'react-native-outside-press';

export default function App() {
  return (
    <EventProvider style={{ flex: 1 }}>
      <RestOfYourApp />
    </EventProvider>
  );
}

The EventProvider component accepts all View’s props.

Then wrap every component you want to detect outside press with OutsidePressHandler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { View } from 'react-native';
import OutsidePressHandler from 'react-native-outside-press';

export default function MyComponent() {
  return (
    <OutsidePressHandler
      onOutsidePress={() => {
        console.log('Pressed outside the box!');
      }}
    >
      <View style={{ height: 200, width: 200, backgroundColor: 'black' }} />
    </OutsidePressHandler>
  );
}

The OutsidePressHandler components accepts all View’s props with 2 additional props named onOutsidePress and disabled.

Now every time we press outside of MyComponent, Pressed outside the box! will be logged.

This post is licensed under CC BY 4.0 by the author.

Generate PKCE challenge in React Native

Use URL class in React Native