Examples
Basic tracking
import React, { useEffect, useRef } from 'react';
import { Button, View } from 'react-native';
import BackgroundGeolocation, {
Subscription,
} from 'react-native-background-geolocation';
export default function App() {
const subscriptions = useRef<Subscription[]>([]);
useEffect(() => {
const subs = subscriptions.current;
// Register event listeners *before* calling ready()
subs.push(
BackgroundGeolocation.onLocation(location => {
console.log('[onLocation]', location);
})
);
// ready() configures the SDK and restores persisted state.
// It does NOT start tracking — call start()/stop() separately.
BackgroundGeolocation.ready({
{{> ts-ready-config.md}}
});
return () => subs.forEach(s => s.remove());
}, []);
// e.g. a toggle-button handler in your UI
const onToggleTracking = async () => {
const state = await BackgroundGeolocation.getState();
if (state.enabled) {
BackgroundGeolocation.stop();
} else {
BackgroundGeolocation.start();
}
console.log('[state]', state.enabled, state.trackingMode);
};
return (
<View>
<Button title="Toggle Tracking" onPress={onToggleTracking} />
</View>
);
}