DEV Community

Julio Xavier
Julio Xavier

Posted on

Using proximity to turn screen black on React Native

Have you ever used a sleep app that asked you to not lock the screen and keep the phone screen flipped to a table/bed during the night? Then, when you do it, the screen magically turns "off"?

Today, I'll show you how to do it using React Native and how it's simple.

First, install react-native-proximity. We aren't using the official lib because right now it doesn't support last React Native versions, so make sure to install it this way:

yarn add pakt-digital/react-native-proximity#584f46494111c639655303cf7e4bae925641dc4a

Install the pods required and build your app again.

cd ios/ && pod install

To make it simpler, we will be building a hook that wraps the proximity listener.

useProximity.js

import { useEffect, useState } from 'react';
import Proximity from 'react-native-proximity';

export default function useProximity() {
  const [hasProximity, setHasProximity] = useState(false);

  useEffect(() => {
    const callback = ({ proximity }) => setHasProximity(!!proximity);
    Proximity.addListener(callback);

    return () => Proximity.removeListener(callback);
  }, []);

  return { hasProximity };
}

Now, you can use your hook on your screen. Notice that BlackScreen and Content are abstractions for a component that should be a black view and your screen content, respectively, like the names suggest.

const Screen = () => {
  const { hasProximity } = useProximity();

  if (hasProximity) return <BlackScreen />;

  return <Content />;
}

Top comments (3)

Collapse
 
vivekshahzymr profile image
Vivek Shah

@julioXavier,

Thanks for this, it works well. My app got black as soon as I put my fingure on proximity sensor.
But I have a different use case, where I want to take a picture of a person when person comes near the device. So my app will stay in the foreground in the kiosk device. And as soon as someone comes near to the device app opens the front camera and clicks a picture of the person and then turns off the camera.

I have tried the original npm package for this but it didn't work well. Detailed git thread is here.
github.com/williambout/react-nativ...

Can you please help me in this with your suggestions?

Collapse
 
juliobetta profile image
Julio Betta

Awesome! btw, this looks very familiar to me... 🧐

Collapse
 
douugbr profile image
Douglas Silva

Hello, I created a wrapper for this specific scenario: npmjs.com/package/react-native-pro...