Skip to content

React Native library to detect clicks outside the component πŸ‘†

License

Notifications You must be signed in to change notification settings

jakex7/react-native-click-outside

Repository files navigation

react-native-click-outside

React Native library to detect clicks outside the component πŸ‘†

Build status - typescript compile License badge Latest, released version Date of latest commit

πŸͺ„ Installation

yarn add react-native-click-outside

πŸ“– Usage

First of all, you need to wrap your app with ClickOutsideProvider as high as possible, for example in App.tsx:

import { ClickOutsideProvider } from 'react-native-click-outside';

export const App = () => (
  <ClickOutsideProvider>
    { /* rest of your app */ }
  </ClickOutsideProvider>
);

Then you can call useClickOutside hook to detect clicks outside the component. First argument is the function that will be called every time user clicks outside of this component. It returns ref that you need to attach to the component you want to detect clicks outside of. For example:

import { useClickOutside } from 'react-native-click-outside';

export default function MyComponent() {
  const ref = useClickOutside<View>(() => console.log('clicked outside A'));
  return (
    <View ref={ref}>
      <Text>Test</Text>
    </View>
  );
}

πŸ› οΈ Troubleshooting

iOS works fine, but Android doesn't

As stated in react-native docs, on Android

Views that are only used to layout their children or otherwise don't draw anything may be automatically removed from the native hierarchy as an optimization.

Source: https://reactnative.dev/docs/view#collapsable-android

If your element is collapsable, it won't be rendered, and therefore you won't be able to detect clicks outside of it. To prevent this, you need to add collapsable={false} prop to the component. For example:

const ref = useClickOutside<View>(() => console.log('clicked outside'));
<View collapsable={false} ref={ref}>
  <Text>Test</Text>
</View>

βš–οΈ License

MIT

πŸ“ Contribute

See the contributing guide to learn how to contribute to the repository and the development workflow.

Built with β™₯️ by Jakub Grzywacz