Back to Home

react-native-ambient-light-module

by Isaías Chávez

React Native module for accessing the device's ambient light sensor. Built with the New Architecture (TurboModules + Fabric), this module provides real-time light data on Android devices.

Features

  • 🚀 Built with React Native New Architecture (TurboModules)
  • 📊 Real-time ambient light sensor data
  • ⚙️ Configurable update intervals
  • 🎯 Smoothing factor for sensor data filtering
  • 📱 Android support with Sensor.TYPE_LIGHT
  • 🔍 Sensor information API (vendor, name, max range, resolution)
  • 📡 Event-based updates

Platform Support

PlatformSupportedNotes
Android✅ YesFull support via Sensor.TYPE_LIGHT
iOS❌ NoApple does not provide public APIs for ambient light sensor access

Installation

npm install react-native-ambient-light-module

or

yarn add react-native-ambient-light-module

iOS Note

While the module will compile and run on iOS, it will always return false for isAvailable() and reject promises with "NOT_SUPPORTED" errors. This is due to platform restrictions.

Usage

Basic Example

import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import * as AmbientLight from 'react-native-ambient-light-module';

function App() {
  const [lux, setLux] = useState(0);

  useEffect(() => {
    // Check if sensor is available
    AmbientLight.isAvailable().then((available) => {
      if (available) {
        // Start receiving updates
        AmbientLight.startUpdates();

        // Listen to ambient light changes
        const subscription = AmbientLight.addAmbientLightListener((event) => {
          setLux(event.lux);
        });

        return () => {
          subscription.remove();
          AmbientLight.stopUpdates();
        };
      }
    });
  }, []);

  return (
    <View>
      <Text>Current Light: {lux.toFixed(2)} lux</Text>
    </View>
  );
}

Advanced Configuration

import * as AmbientLight from 'react-native-ambient-light-module';

// Set update interval to 500ms
AmbientLight.setUpdateInterval(500);

// Set smoothing factor (0.0 = no smoothing, 1.0 = maximum smoothing)
AmbientLight.setSmoothingFactor(0.7);

// Get current illuminance value
const { lux } = await AmbientLight.getCurrentIlluminance();

// Get sensor information
const sensorInfo = await AmbientLight.getSensorInfo();
console.log(sensorInfo);
// {
//   vendor: "Google Inc.",
//   name: "Light Sensor",
//   maxRange: 65535.0,
//   resolution: 1.0
// }

API Reference

Methods

isAvailable(): Promise<boolean>

Check if the ambient light sensor is available on the device.

Returns: Promise<boolean> - true on Android devices with light sensor, false on iOS or devices without sensor.

Example:

const available = await AmbientLight.isAvailable();

startUpdates(): void

Start receiving ambient light sensor updates. This will trigger the ambientLightDidUpdate event.

Note: Only works on Android. No-op on iOS.

Example:

AmbientLight.startUpdates();

stopUpdates(): void

Stop receiving ambient light sensor updates.

Example:

AmbientLight.stopUpdates();

setUpdateInterval(ms: number): void

Set the update interval for sensor readings.

Parameters:

  • ms - Update interval in milliseconds (minimum: 100ms)

Example:

AmbientLight.setUpdateInterval(1000); // Update every 1 second

getCurrentIlluminance(): Promise<{ lux: number }>

Get the current illuminance value from the sensor.

Returns: Promise<{ lux: number }> - Current illuminance in lux

Throws: Rejects with error on iOS or if sensor is unavailable

Example:

const result = await AmbientLight.getCurrentIlluminance();
console.log(result.lux); // e.g., 245.5

setSmoothingFactor(value: number): void

Set smoothing factor for sensor data filtering using exponential moving average.

Parameters:

  • value - Smoothing factor between 0.0 and 1.0
    • 0.0 = No smoothing (more responsive, more noise)
    • 1.0 = Maximum smoothing (less responsive, less noise)
    • Default: 0.5

Example:

AmbientLight.setSmoothingFactor(0.5);

getSensorInfo(): Promise<SensorInfo>

Get information about the ambient light sensor hardware.

Returns: Promise<SensorInfo> with:

interface SensorInfo {
  vendor: string;      // Sensor vendor name
  name: string;        // Sensor name
  maxRange: number;    // Maximum range in lux
  resolution: number;  // Resolution in lux
}

Throws: Rejects with error on iOS or if sensor is unavailable

Example:

const info = await AmbientLight.getSensorInfo();

addAmbientLightListener(listener)

Add a listener for ambient light updates.

Parameters:

  • listener - Callback function that receives:
    {
      lux: number;       // Illuminance in lux
      timestamp: number; // Timestamp in milliseconds
    }

Returns: Subscription object with remove() method

Example:

const subscription = AmbientLight.addAmbientLightListener((event) => {
  console.log(`Lux: ${event.lux}, Time: ${event.timestamp}`);
});

// Later, remove the listener
subscription.remove();

removeAllListeners(): void

Remove all ambient light event listeners.

Example:

AmbientLight.removeAllListeners();

Events

ambientLightDidUpdate

Emitted when the ambient light sensor detects a change (based on update interval).

Event payload:

{
  lux: number;       // Current illuminance in lux
  timestamp: number; // Timestamp in milliseconds
}

Understanding Lux Values

Here are typical lux values for reference:

ConditionLux Value
Moonless night< 0.01
Full moon~0.25
Dark room~10
Office lighting320-500
Overcast day~1,000
Full daylight10,000-25,000
Direct sunlight32,000-100,000

Limitations

iOS Platform

Apple does not provide public APIs to access the ambient light sensor on iOS devices. While the module will compile on iOS:

  • isAvailable() will always return false
  • getCurrentIlluminance() and getSensorInfo() will reject with "NOT_SUPPORTED" error
  • Control methods (startUpdates, stopUpdates, etc.) are no-ops
  • No events are emitted

Android Platform

  • Not all Android devices have ambient light sensors
  • Sensor accuracy varies by device manufacturer
  • Sensor readings may be affected by screen protectors or cases covering the sensor

License

MIT


Made with create-react-native-library