Check if screen is getting blurred or focus in React native? - react-native

i am using this
useEffect(() => {
const navFocusListener = navigation.addListener('didFocus', () => {
console.log('focus');
});
return () => {
navFocusListener.remove();
};
}, []);
I am using this code also tried other listeners. but there is no benefit, i am using react-native-immediate-call package for ussd dialing but as it doesn't have any callback. So i i call this function a dialer open for dialing for the USSD code. So now i want that when ussd dialing completes then comes back to screen and a api will call to get response. So how can i detect that USSD dialing is running running or completed so that i can make a request to the api.

For focus listener; you must change 'didFocus' to 'focus', If you are using react navigation v5+ and you should update like below:
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// do something
});
return unsubscribe;
}, []);
You can examine its documentation from here.

in react-navigation 5 you can do this to check screen is focus or blur,
try this in react navigation 5 using usefocuseffect-hook
useEffect(
() => navigation.addListener('focus', () => {}),
[navigation]
);
useEffect(
() => navigation.addListener('blur', () => {}),
[navigation]
);

Try this thanks
import { NavigationEvents } from "react-navigation";
callback=()=>{
alert('I m always working when you come this Screen')
}
in return (
<Your Code>
<NavigationEvents onWillFocus={() => callback()} />
<Your Code/>
)

Actually, you need to detect app state if it is in foreground or background or needs to add callback function into react-native-immediate-call by writing native code of android or ios package like this
import React, { useRef, useState, useEffect } from "react";
import { AppState, StyleSheet, Text, View } from "react-native";
const AppStateExample = () => {
const appState = useRef(AppState.currentState);
const [appStateVisible, setAppStateVisible] = useState(appState.current);
useEffect(() => {
AppState.addEventListener("change", _handleAppStateChange);
return () => {
AppState.removeEventListener("change", _handleAppStateChange);
};
}, []);
const _handleAppStateChange = (nextAppState) => {
if (
appState.current.match(/inactive|background/) &&
nextAppState === "active"
) {
console.log("App has come to the foreground!");
}
appState.current = nextAppState;
setAppStateVisible(appState.current);
console.log("AppState", appState.current);
};
return (
<View style={styles.container}>
<Text>Current state is: {appStateVisible}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
});
export default AppStateExample;

Related

How to use `expo-splash-screen` with `expo-google-fonts`?

The splash screen is using async operations to wait, while the fonts package is using a "custom hook" useFonts (I guess).
How to make the splash screen wait for the google fonts to load?
You can load fonts with loadAsync from expo-fonts, and manage splash screen with expo-splash-screen
import * as SplashScreen from 'expo-splash-screen';
import * as Font from 'expo-font';
import { Inter_900Black } from '#expo-google-fonts/inter';
export default function App() {
const [appIsReady, setAppIsReady] = useState(false);
useEffect(() => {
(async () => {
try {
await SplashScreen.preventAutoHideAsync();
await Font.loadAsync({ Inter_900Black });
}
catch {
// handle error
}
finally {
setAppIsReady(true);
}
})();
}, []);
const onLayout = useCallback(() => {
if (appIsReady) {
SplashScreen.hideAsync();
}
}, [appIsReady]);
if (!appIsReady) {
return null;
}
return (
<View style={styles.container} onLayout={onLayout}>
<Text style={{fontFamily: 'Inter_900Black'}}>
Example text
</Text>
</View>
);
}
This is compete!
import React, { useCallback, useEffect, useState } from 'react';
import * as SplashScreen from 'expo-splash-screen';
import * as Font from 'expo-font';
import { Montserrat_400Regular, Montserrat_500Medium, Montserrat_700Bold,
Montserrat_900Black } from '#expo-google-fonts/montserrat';
export default function App() {
const [appIsReady, setAppIsReady] = useState(false);
useEffect(() => {
async function prepare() {
try {
// Keep the splash screen visible while we fetch resources
await SplashScreen.preventAutoHideAsync();
// Pre-load fonts, make any API calls you need to do here
await Font.loadAsync({ Montserrat_900Black });
// Artificially delay for two seconds to simulate a slow loading
// experience. Please remove this if you copy and paste the code!
await new Promise(resolve => setTimeout(resolve, 2000));
} catch (e) {
console.warn(e);
} finally {
// Tell the application to render
setAppIsReady(true);
}
}
prepare();
}, []);
const onLayoutRootView = useCallback(async () => {
if (appIsReady) {
// This tells the splash screen to hide immediately! If we call this after
// `setAppIsReady`, then we may see a blank screen while the app is
// loading its initial state and rendering its first pixels. So instead,
// we hide the splash screen once we know the root view has already
// performed layout.
await SplashScreen.hideAsync();
}
}, [appIsReady]);
if (!appIsReady) {
return null;
}
return (
<View
style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}
onLayout={onLayoutRootView}>
<Text style={{ fontFamily: 'Montserrat_900Black', fontSize: 18 }}>SplashScreen
Demo! 👋</Text>
</View>
);
}'

Geolocation clearWatch(watchId) does not stop location tracking (React Native)

I'm trying to create simple example of location tracker and I'm stuck with following case. My basic goal is to toggle location watch by pressing start/end button. I'm doing separation of concerns by implementing custom react hook which is then used in App component:
useWatchLocation.js
import {useEffect, useRef, useState} from "react"
import {PermissionsAndroid} from "react-native"
import Geolocation from "react-native-geolocation-service"
const watchCurrentLocation = async (successCallback, errorCallback) => {
if (!(await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION))) {
errorCallback("Permissions for location are not granted!")
}
return Geolocation.watchPosition(successCallback, errorCallback, {
timeout: 3000,
maximumAge: 500,
enableHighAccuracy: true,
distanceFilter: 0,
useSignificantChanges: false,
})
}
const stopWatchingLocation = (watchId) => {
Geolocation.clearWatch(watchId)
// Geolocation.stopObserving()
}
export default useWatchLocation = () => {
const [location, setLocation] = useState()
const [lastError, setLastError] = useState()
const [locationToggle, setLocationToggle] = useState(false)
const watchId = useRef(null)
const startLocationWatch = () => {
watchId.current = watchCurrentLocation(
(position) => {
setLocation(position)
},
(error) => {
setLastError(error)
}
)
}
const cancelLocationWatch = () => {
stopWatchingLocation(watchId.current)
setLocation(null)
setLastError(null)
}
const setLocationWatch = (flag) => {
setLocationToggle(flag)
}
// execution after render when locationToggle is changed
useEffect(() => {
if (locationToggle) {
startLocationWatch()
} else cancelLocationWatch()
return cancelLocationWatch()
}, [locationToggle])
// mount / unmount
useEffect(() => {
cancelLocationWatch()
}, [])
return { location, lastError, setLocationWatch }
}
App.js
import React from "react"
import {Button, Text, View} from "react-native"
import useWatchLocation from "./hooks/useWatchLocation"
export default App = () => {
const { location, lastError, setLocationWatch } = useWatchLocation()
return (
<View style={{ margin: 20 }}>
<View style={{ margin: 20, alignItems: "center" }}>
<Text>{location && `Time: ${new Date(location.timestamp).toLocaleTimeString()}`}</Text>
<Text>{location && `Latitude: ${location.coords.latitude}`}</Text>
<Text>{location && `Longitude: ${location.coords.longitude}`}</Text>
<Text>{lastError && `Error: ${lastError}`}</Text>
</View>
<View style={{ marginTop: 20, width: "100%", flexDirection: "row", justifyContent: "space-evenly" }}>
<Button onPress={() => {setLocationWatch(true)}} title="START" />
<Button onPress={() => {setLocationWatch(false)}} title="STOP" />
</View>
</View>
)
}
I have searched multiple examples which are online and code above should work. But the problem is when stop button is pressed location still keeps getting updated even though I invoke Geolocation.clearWatch(watchId).
I wrapped Geolocation calls to handle location permission and other possible debug stuff. It seems like watchId value that is saved using useRef hook inside useWatchLocation is invalid. My guess is based on attempting to call Geolocation.stopObserving() right after Geolocation.clearWatch(watchId). Subscription stops but I get warning:
Called stopObserving with existing subscriptions.
So I assume that original subscription was not cleared.
What am I missing/doing wrong?
EDIT: I figured out solution. But since isMounted pattern is generally considered antipattern: Does anyone have a better solution?
Ok, problem solved with isMounted pattern. isMounted.current is set at locationToggle effect to true and inside cancelLocationWatch to false:
const isMounted = useRef(null)
...
useEffect(() => {
if (locationToggle) {
isMounted.current = true // <--
startLocationWatch()
} else cancelLocationWatch()
return () => cancelLocationWatch()
}, [locationToggle])
...
const cancelLocationWatch = () => {
stopWatchingLocation(watchId.current)
setLocation(null)
setLastError(null)
isMounted.current = false // <--
}
And checked at mount / unmount effect, success and error callback:
const startLocationWatch = () => {
watchId.current = watchCurrentLocation(
(position) => {
if (isMounted.current) { // <--
setLocation(position)
}
},
(error) => {
if (isMounted.current) { // <--
setLastError(error)
}
}
)
}

How to open app settings page in react native android?

At the end react native bridge is the only way.But is there any npm package which has been worked successfully for anyone?
You can open your app settings by using Linking library.
import {Linking} from 'react-native';
Linking.openSettings();
Offical document: https://reactnative.dev/docs/linking#opensettings
You can use #react-native-community/react-native-permissions library.
Here offical documantation: https://github.com/react-native-community/react-native-permissions#opensettings
Example:
import { openSettings } from 'react-native-permissions';
openSettings();
combining the existing answers: this works for me for both iOS and Android (without expo)
import { Linking, Platform } from 'react-native';
const handleOpenSettings = () => {
if (Platform.OS === 'ios') {
Linking.openURL('app-settings:');
} else {
Linking.openSettings();
}
};
// add a button that calls handleOpenSetttings()
Use
IntentLauncher.startActivity({
action: 'android.settings.SETTINGS',
})
instead of
IntentLauncher.startActivity({
action: 'android.settings.APPLICATION_DETAILS_SETTINGS',
data: 'package:' + pkg
})
Like
import IntentLauncher, { IntentConstant } from 'react-native-intent-launcher'
const openAppSettings = () => {
if (Platform.OS === 'ios') {
Linking.openURL('app-settings:')
} else {
IntentLauncher.startActivity({
action: 'android.settings.SETTINGS',
})
}
}
ANDROID
Wifi
IntentLauncher.startActivity({
action: 'android.settings.SETTINGS'
})
GPS
IntentLauncher.startActivity({
action: 'android.settings.LOCATION_SOURCE_SETTINGS'
})
IOS
WIFI
Linking.openURL("App-Prefs:root=WIFI");
GPS
Linking.openURL('App-Prefs:Privacy&path=LOCATION')
Linking API from react-native core provides the function to send custom intent action to Android.
NOTE - You can send any custom action that is acceptable by android moreover you can also pass data to the intent.
Here is an example to open settings :
import {Linking} from 'react-native';
// To open settings
Linking.sendIntent('android.settings.SETTINGS');
// To open GPS Location setting
Linking.sendIntent('android.settings.LOCATION_SOURCE_SETTINGS');
Hope this will help you or somebody else. Thanks!
Happy Coding :-)
This is a complete answer for both android & iOS.
Without Expo:
import DeviceInfo from 'react-native-device-info';
import IntentLauncher, { IntentConstant } from 'react-native-intent-launcher'
const pkg = DeviceInfo.getBundleId();
const openAppSettings = () => {
if (Platform.OS === 'ios') {
Linking.openURL('app-settings:')
} else {
IntentLauncher.startActivity({
action: 'android.settings.APPLICATION_DETAILS_SETTINGS',
data: 'package:' + pkg
})
}
}
With Expo:
import Constants from 'expo-constants'
import * as IntentLauncher from 'expo-intent-launcher'
const pkg = Constants.manifest.releaseChannel
? Constants.manifest.android.package
: 'host.exp.exponent'
const openAppSettings = () => {
if (Platform.OS === 'ios') {
Linking.openURL('app-settings:')
} else {
IntentLauncher.startActivityAsync(
IntentLauncher.ACTION_APPLICATION_DETAILS_SETTINGS,
{ data: 'package:' + pkg },
)
}
}
import React, { useCallback } from "react";
import { Button, Linking, StyleSheet, View } from "react-native";
const OpenSettingsButton = ({ children }) => {
const handlePress = useCallback(async () => {
// Open the custom settings if the app has one
await Linking.openSettings();
}, []);
return <Button title={children} onPress={handlePress} />;
};
const App = () => {
return (
<View style={styles.container}>
<OpenSettingsButton>Open Settings</OpenSettingsButton>
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: "center", alignItems: "center" },
});
import { Linking, Platform } from 'react-native';
const openSettingsAlert = () =>
Alert.alert('Please provide the require permission from settings', '', [
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{ text: 'Go To Settings', onPress: () => openSettings() },
]);
const openSettings = () => {
if (Platform.OS === 'ios') {
Linking.openURL('app-settings:');
} else {
Linking.openSettings();
}
};
let isStoragePermitted = await requestExternalWritePermission();
if (isStoragePermitted === true) {
}else{
console.log('permission not granted');
openSettingsAlert();
}
const requestExternalWritePermission = async () => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
);
// If WRITE_EXTERNAL_STORAGE Permission is granted
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
alert('Storage Access permission error:', err);
}
return false;
}
};

React-Native + Enzyme + Jest: How to test platform specific behaviour?

TLDR: How can I tell my Enzyme / Jest test it should run the tests as if it was running on iOS? I want to test platform specific behaviour.
I'm building a custom status bar component that adds 20 pixels of height, if it runs on iOS to prevent my content from overlapping with the status bar. (Yes, I know React-Navigation has a SafeAreaView, but this only works for iPhone X, not for e.g. iPad.)
Here is my component:
import React from "react";
import { StatusBar as ReactNativeStatusBar, View } from "react-native";
import styles from "./styles";
const StatusBar = ({ props }) => (
<View style={styles.container}>
<ReactNativeStatusBar {...props} />
</View>
);
export default StatusBar;
Here is the styles.js file:
import { StyleSheet, Platform } from "react-native";
const height = Platform.OS === "ios" ? 20 : 0;
const styles = StyleSheet.create({
container: {
height: height
}
});
export default styles;
And here are the tests so far:
import React from "react";
import { shallow } from "enzyme";
import { View } from "react-native";
import StatusBar from "./StatusBar";
const createTestProps = props => ({
...props
});
describe("StatusBar", () => {
describe("rendering", () => {
let wrapper;
let props;
beforeEach(() => {
props = createTestProps();
wrapper = shallow(<StatusBar {...props} />);
});
it("should render a <View />", () => {
expect(wrapper.find(View)).toHaveLength(1);
});
it("should give the <View /> the container style", () => {
expect(wrapper.find(View)).toHaveLength(1);
});
it("should render a <StatusBar />", () => {
expect(wrapper.find("StatusBar")).toHaveLength(1);
});
});
});
Now what I would like to do is add two more describe areas that explicitly test for the height to be either 20 on iOS or 0 or Android. The problem is I couldn't find how to emulate the platform with Enzyme / Jest tests.
So how do I tell my test suite that it should run the code for the respective platform?
You can override the RN Platform object and perform different tests for each platform. Here's an example for how a test file would like like:
describe('tests', () => {
let Platform;
beforeEach(() => {
Platform = require('react-native').Platform;
});
describe('ios tests', () => {
beforeEach(() => {
Platform.OS = 'ios';
});
it('should test something on iOS', () => {
});
});
describe('android tests', () => {
beforeEach(() => {
Platform.OS = 'android';
});
it('should test something on Android', () => {
});
});
});
By the way, regardless of the question about testing, setting the status-bar height to 20 on iOS is wrong since it can have different sizes on different devices (iPhone X for example)

How to detect when keyboard is opened or closed in React Native

How to detect if user close the keyboard in react native, I want to call a function when user closed the keyboard.
and if you can answer to detect keyboard is open too it will be appreciated, thanks.
I'm on the react native latest version 0.56
Thank you guys for your answers. Here is the hooks version if someone is interested:
const [isKeyboardVisible, setKeyboardVisible] = useState(false);
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
() => {
setKeyboardVisible(true); // or some other action
}
);
const keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
() => {
setKeyboardVisible(false); // or some other action
}
);
return () => {
keyboardDidHideListener.remove();
keyboardDidShowListener.remove();
};
}, []);
1. You can use Keyboard class from facebook.
Here is a sample code.
import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';
class Example extends Component {
componentWillMount () {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
}
componentWillUnmount () {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow () {
alert('Keyboard Shown');
}
_keyboardDidHide () {
alert('Keyboard Hidden');
}
render() {
return (
<TextInput
onSubmitEditing={Keyboard.dismiss}
/>
);
}
}
###2. You can use some other npm dependency also, like react-native-keyboard-listener.
Import the component into the file you want to use it:
import KeyboardListener from 'react-native-keyboard-listener';
Use the component directly in your code. The component won't render anything
<View>
<KeyboardListener
onWillShow={() => { this.setState({ keyboardOpen: true }); }}
onWillHide={() => { this.setState({ keyboardOpen: false }); }}
/>
</View>
To install this dependency run below command.
npm install --save react-native-keyboard-listener
Choose any you feel more convenient.
I wrapped this up in a hook:
import { useState, useEffect } from 'react';
import { Keyboard } from 'react-native';
export const useKeyboardVisible = () => {
const [isKeyboardVisible, setKeyboardVisible] = useState(false);
useEffect(() => {
const keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
() => {
setKeyboardVisible(true);
},
);
const keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
() => {
setKeyboardVisible(false);
},
);
return () => {
keyboardDidHideListener.remove();
keyboardDidShowListener.remove();
};
}, []);
return isKeyboardVisible;
};
The hook returns a boolean flag that can be used to apply logic conditionally or run any other effect needed.
Improved version of #Khemraj 's answer (which worked great for me) with bound methods to the instance in order to be able to update the component's state from the listener and re-render.
import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';
class Example extends Component {
state = {
keyboardState: 'closed'
}
componentWillMount () {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
}
componentWillUnmount () {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow = () => {
this.setState({
keyboardState: 'opened'
});
}
_keyboardDidHide = () => {
this.setState({
keyboardState: 'closed'
});
}
render() {
return (
<TextInput
onSubmitEditing={Keyboard.dismiss}
/>
);
}
}
I came across the usekeyboard hook found in #react-native-community/hooks
E.g.
import { useKeyboard } from '#react-native-community/hooks'
const keyboard = useKeyboard()
console.log('keyboard isKeyboardShow: ', keyboard.keyboardShown)
console.log('keyboard keyboardHeight: ', keyboard.keyboardHeight)
Source: https://github.com/react-native-community/hooks/blob/master/src/useKeyboard.ts
I used a small remix to the great answer from #halbano that may be useful to consider depending on your situation
export default function useKeyboardOffsetHeight(): number {
const [keyBoardOffsetHeight, setKeyboardOffsetHeight] = useState(0);
useEffect(() => {
const keyboardWillShowListener = Keyboard.addListener(
"keyboardWillShow",
(e) => {
setKeyboardOffsetHeight(e.endCoordinates.height);
}
);
const keyboardWillHideListener = Keyboard.addListener(
"keyboardWillHide",
() => {
setKeyboardOffsetHeight(0);
}
);
return () => {
keyboardWillHideListener.remove();
keyboardWillShowListener.remove();
};
}, []);
return keyBoardOffsetHeight;
}
keyBoardOffsetHeight vs isKeyboardVisible
I used integer keyBoardOffsetHeight instead of boolean isKeyboardVisible . Since it's often useful to move some of your other components based on the keyboard size. The offset is either 0 (hidden) or Y > 0 pixels (it is shown). Then I can use that in styling like so:
const keyBoardOffsetHeight = useKeyboardOffsetHeight();
...
<View
style={{
bottom: keyBoardOffsetHeight,
}}
>
keyboardWillShow vs keyboardDidShow
Secondly, I use keyboardWillShow events so that I can anticipate the keyboard appearing and fire my UI changes earlier.
The keyboardDidShow event fires once the keyboard has already appeared.
I also used keyboardWillHide instead of keyboardDidHide based on the same reasoning.
MobX version:
import { observable } from 'mobx'
import { EmitterSubscription, Keyboard } from 'react-native'
class KeyboardStore {
#observable isKeyboardVisible = false
keyboardSubs: EmitterSubscription[] = []
subKeyboard() {
this.keyboardSubs = [
Keyboard.addListener('keyboardDidShow', () => this.isKeyboardVisible = true),
Keyboard.addListener('keyboardDidHide', () => this.isKeyboardVisible = false),
]
}
unsubKeyboard() {
this.keyboardSubs.forEach(sub => sub.remove())
this.keyboardSubs = []
}
}
and inside top level App component
useEffect(() => {
store.subKeyboard()
return () => {
store.unsubKeyboard()
}
}, [])
and check anywhere in your app with store.isKeyboardVisible.
All the thing already avalable in react-native Keyboard class
import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';
class Example extends Component {
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
this.keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this._keyboardWillShow);
this.keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', this._keyboardWillHide);
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
this.keyboardWillShowListener.remove();
this.keyboardWillHideListener.remove();
}
_keyboardWillShow() {
console.log('Keyboard Showning')
}
_keyboardWillHide() {
console.log('Keyboard Heding')
}
_keyboardDidShow() {
alert('Keyboard Shown');
}
_keyboardDidHide() {
alert('Keyboard Hidden');
}
render() {
return (
<TextInput
onSubmitEditing={Keyboard.dismiss}
/>
);
}
}