react-native#Platform TypeScript Examples
The following examples show how to use
react-native#Platform.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From protect-scotland with Apache License 2.0 | 7 votes |
export async function saveMetric({event = ''}) {
try {
const analyticsOptin = await SecureStore.getItemAsync('analyticsConsent');
if (!analyticsOptin || (analyticsOptin && analyticsOptin !== 'true')) {
return false;
}
const version = await getVersion();
const os = Platform.OS;
const req = await request(`${urls.api}/metrics`, {
authorizationHeaders: true,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
os,
version: version.display,
event
})
});
return req && req.status === 204;
} catch (err) {
console.log(err);
return false;
}
}
Example #2
Source File: utils.ts From react-native-actions-sheet with MIT License | 7 votes |
export function getDeviceHeight(statusBarTranslucent: boolean | undefined):number {
var height = Dimensions.get("window").height;
if (Platform.OS === "android" && !statusBarTranslucent) {
return StatusBar.currentHeight ? height - StatusBar.currentHeight : height;
}
return height;
}
Example #3
Source File: ImageIcon.tsx From ReactNative-UIKit with MIT License | 6 votes |
ImageIcon: React.FC<ImageIconInterface> = (props) => {
const {styleProps} = useContext(PropsContext);
const {theme} = styleProps || {};
const imageRef = React.useRef(null);
useImageDelay(imageRef, 10, props?.name || '', props?.color);
return (
<Image
ref={Platform.OS === 'web' ? imageRef : undefined}
style={[
{
width: '100%',
height: '100%',
tintColor: props.color || theme || '#fff',
},
props.style as object,
]}
resizeMode={'contain'}
source={{uri: props.name ? icons[props.name] : props.icon}}
/>
);
}
Example #4
Source File: index.tsx From react-native-detector with MIT License | 6 votes |
addScreenshotListener = Platform.select<
(listener: () => void) => Unsubscribe
>({
default: (): Unsubscribe => () => {},
ios: commonAddScreenshotListener,
android: (listener: () => void): Unsubscribe => {
if (getListenersCount() === 0) {
Detector.startScreenshotDetection();
}
const unsubscribe: Unsubscribe = commonAddScreenshotListener(listener);
return () => {
unsubscribe();
if (getListenersCount() === 0) {
Detector.stopScreenshotDetection();
}
};
},
})
Example #5
Source File: TouchableIcon.tsx From mobile with Apache License 2.0 | 6 votes |
TouchableIcon = ({iconName, iconSize, containerSize = 56, label, onPress}: TouchableIconProps) => {
const accessibilityProps = {
accessibilityRole: 'button' as 'button',
accessibilityLabel: label,
};
const content = (
<Box width={containerSize} height={containerSize} justifyContent="center" alignItems="center">
<Icon name={iconName} size={iconSize} />
</Box>
);
if (Platform.OS === 'android') {
return (
<Ripple
rippleSize={containerSize}
rippleContainerBorderRadius={containerSize}
rippleCentered
onPress={onPress}
{...accessibilityProps}
>
{content}
</Ripple>
);
}
return (
<TouchableOpacity onPress={onPress} {...accessibilityProps}>
{content}
</TouchableOpacity>
);
}
Example #6
Source File: Bar.tsx From expo-progress with MIT License | 6 votes |
function useCode(nodeFactory, dependencies) {
if (!(React.useEffect instanceof Function)) return;
// @ts-ignore
React.useEffect(() => {
// check and correct 1st parameter
if (!(nodeFactory instanceof Function)) {
console.warn(
'useCode() first argument should be a function that returns an animation node.'
);
const node = nodeFactory;
nodeFactory = () => node;
}
let node = nodeFactory();
if (node) {
// allow factory to return array
if (node instanceof Array) node = block(node);
const animatedAlways = always(node);
animatedAlways.__attach();
// todo: upstream this
if (Platform.OS === 'web') {
animatedAlways.__onEvaluate();
}
// return undo function
return () => animatedAlways.__detach();
}
}, dependencies);
}
Example #7
Source File: fonts.tsx From frontatish with MIT License | 6 votes |
type = {
base: 'Avenir-Book',
bold: 'Avenir-Black',
notoserif: 'notoserif',
sans_serif: 'sans-serif',
sans_serif_light: 'sans-serif-light',
sans_serif_thin: 'sans-serif-thin',
sans_serif_condensed: 'sans-serif-condensed',
sans_serif_medium: 'sans-serif-medium',
serif: 'serif',
roboto: 'Roboto',
monospace: 'monospace',
// gotham_book:'GothamBook',
// gotham_bold:'GothamBold',
// gotham_medium:'GothamMedium',
gotham_book: Platform.OS === 'ios' ? 'Avenir-Book' : 'roboto.regular',
gotham_bold: Platform.OS === 'ios' ? 'Avenir-Book' : 'roboto.bold',
gotham_medium: Platform.OS === 'ios' ? 'Avenir-Book' : 'roboto.medium',
}
Example #8
Source File: env.ts From companion-kit with MIT License | 6 votes |
function getFirebaseConfig() {
const original = process.firebase;
const override = process.firebaseForPlatform;
const overrideForPlatform = override && override[Platform.OS];
if (overrideForPlatform) {
return Object.assign(original, overrideForPlatform);
}
return original;
}
Example #9
Source File: NoGPS.tsx From hamagen-react-native with MIT License | 6 votes |
NoGPS = ({ title, description, button }: Props) => {
// open settings IOS
const handlePressIOS = () => Linking.openURL('App-prefs:root=Privacy&path=LOCATION');
// open Location settings Android
const handlePressAndroid = () => {
RNSettings.openSetting(RNSettings.ACTION_LOCATION_SOURCE_SETTINGS);
};
return (
<FadeInView style={styles.container}>
<Icon source={require('../../assets/main/noData.png')} width={IS_SMALL_SCREEN ? 80 : 113} height={IS_SMALL_SCREEN ? 100 : 143} />
<View>
<Text style={[styles.text, { fontSize: 22 }]} bold>{title}</Text>
<Text style={styles.text}>{description}</Text>
</View>
<TouchableOpacity
onPress={Platform.select({
ios: handlePressIOS,
android: handlePressAndroid
})}
>
<Text style={{ fontSize: 16, paddingHorizontal: 5 }} bold>{button}</Text>
<View style={{ height: 2, backgroundColor: MAIN_COLOR, marginTop: 2 }} />
</TouchableOpacity>
<View />
</FadeInView>
);
}
Example #10
Source File: App.tsx From react-native-twilio-phone with MIT License | 6 votes |
async function fetchAccessToken() {
const response = await fetch(
'https://XXXXXX.ngrok.io/accessToken?identity=' +
identity +
'&os=' +
Platform.OS
);
const accessToken = await response.text();
return accessToken;
}
Example #11
Source File: go-to-settings.tsx From protect-scotland with Apache License 2.0 | 6 votes |
goToSettingsAction = async (
bluetoothDisabled?: boolean,
askPermissions?: () => Promise<void>
) => {
try {
if (Platform.OS === 'ios') {
Linking.openSettings();
} else {
bluetoothDisabled
? await IntentLauncher.startActivityAsync(
IntentLauncher.ACTION_SETTINGS
)
: await askPermissions!();
}
} catch (err) {
console.log('Error handling go to settings', err);
}
}
Example #12
Source File: Recorder.tsx From leopard with Apache License 2.0 | 6 votes |
constructor() {
if (Platform.OS === 'android') {
this._recordingPath = `${RNFS.DocumentDirectoryPath}/recording.wav`;
} else if (Platform.OS === 'ios') {
this._recordingPath = `${RNFS.MainBundlePath}/recording.wav`;
} else {
throw new Error('Unsupported platform');
}
}
Example #13
Source File: StyleHelper.ts From react-native-design-kit with MIT License | 6 votes |
export function getStyleShadow(): ViewStyle {
return {
...Platform.select({
android: {
elevation: 4,
},
ios: {
shadowColor: 'darkgray',
shadowOffset: {height: 1, width: 1},
shadowOpacity: 1,
shadowRadius: 1,
},
}),
};
}
Example #14
Source File: updateChecker.tsx From SQL-Play with GNU Affero General Public License v3.0 | 6 votes |
inAppUpdates
.checkNeedsUpdate()
.then(result => {
if (result.shouldUpdate) {
let updateOptions: StartUpdateOptions = {};
if (Platform.OS === 'android') {
// android only, on iOS the user will be promped to go to your app store page
updateOptions = {
updateType: IAUUpdateKind.FLEXIBLE,
};
}
inAppUpdates.startUpdate(updateOptions);
}
})
.catch(_ => console.log('failed to check for updates'));
Example #15
Source File: App.tsx From sp-react-native-in-app-updates with MIT License | 6 votes |
startUpdating = () => {
if (this.state.needsUpdate) {
let updateOptions: StartUpdateOptions = {};
if (Platform.OS === 'android' && this.state.otherData) {
const { otherData } = this.state || {
otherData: null,
};
// @ts-expect-error TODO: Check if updatePriority exists
if (otherData?.updatePriority >= HIGH_PRIORITY_UPDATE) {
updateOptions = {
updateType: IAUUpdateKind.IMMEDIATE,
};
} else {
updateOptions = {
updateType: IAUUpdateKind.FLEXIBLE,
};
}
}
this.inAppUpdates.addStatusUpdateListener(this.onStatusUpdate);
this.inAppUpdates.startUpdate(updateOptions);
} else {
// @ts-ignore
alert('doesnt look like we need an update');
}
};
Example #16
Source File: gitlab.tsx From THUInfo with MIT License | 6 votes |
BranchItem = ({
name,
onPress,
}: {
name: string;
onPress: (event: GestureResponderEvent) => void;
}) => {
const themeName = useColorScheme();
const {colors} = themes(themeName);
const content = (
<View
style={{
padding: 8,
paddingRight: 16,
flexDirection: "row",
justifyContent: "space-between",
}}>
<Text style={{fontSize: 17, marginHorizontal: 10, color: colors.text}}>
{name}
</Text>
</View>
);
return Platform.OS === "ios" ? (
<TouchableHighlight underlayColor="#0002" onPress={onPress}>
{content}
</TouchableHighlight>
) : (
<TouchableNativeFeedback
background={TouchableNativeFeedback.Ripple("#0002", false)}
onPress={onPress}>
{content}
</TouchableNativeFeedback>
);
}
Example #17
Source File: index.ts From clipped-tabbar with BSD 3-Clause "New" or "Revised" License | 6 votes |
IS_IPHONE_X = (() => {
if (Platform.OS === 'web') {
return false;
}
return (
(Platform.OS === 'ios' &&
((D_HEIGHT === X_HEIGHT && D_WIDTH === X_WIDTH) ||
(D_HEIGHT === X_WIDTH && D_WIDTH === X_HEIGHT))) ||
(D_HEIGHT === XSMAX_HEIGHT && D_WIDTH === XSMAX_WIDTH) ||
(D_HEIGHT === XSMAX_WIDTH && D_WIDTH === XSMAX_HEIGHT)
);
})()
Example #18
Source File: App.tsx From react-native-network-logger with MIT License | 6 votes |
themedStyles = (dark = false) =>
StyleSheet.create({
container: {
flex: 1,
backgroundColor: dark ? '#2d2a28' : 'white',
paddingTop: Platform.OS === 'android' ? 25 : 0,
},
header: {
flexDirection: 'row',
},
navButton: {
flex: 1,
},
backButtonText: {
color: dark ? 'white' : 'black',
paddingHorizontal: 20,
fontSize: 30,
fontWeight: 'bold',
},
title: {
flex: 5,
color: dark ? 'white' : 'black',
textAlign: 'center',
padding: 10,
fontSize: 18,
fontWeight: 'bold',
},
bottomView: {
flexDirection: 'row',
justifyContent: 'space-between',
paddingHorizontal: 30,
},
})
Example #19
Source File: react-native-file-access.ts From react-native-file-access with MIT License | 6 votes |
/**
* Return the local storage directory for app groups.
*
* This is an Apple only feature.
*/
public getAppGroupDir = jest.fn((groupName: string) => {
if (Platform.OS !== 'ios' && Platform.OS !== 'macos') {
throw new Error('AppGroups are available on Apple devices only');
}
return `${Dirs.DocumentDir}/shared/AppGroup/${groupName}`;
});
Example #20
Source File: index.tsx From react-native-actions-sheet with MIT License | 6 votes |
componentDidMount() {
this.props.id && SheetManager.add(this.props.id);
this.keyboardShowSubscription = Keyboard.addListener(
Platform.OS === "android" ? "keyboardDidShow" : "keyboardWillShow",
this._onKeyboardShow
);
this.KeyboardHideSubscription = Keyboard.addListener(
Platform.OS === "android" ? "keyboardDidHide" : "keyboardWillHide",
this._onKeyboardHide
);
if (this.props.id) {
this.sheetManagerShowEvent = DeviceEventEmitter.addListener(
`show_${this.props.id}`,
this.onSheetManagerShow
);
this.sheetManagerHideEvent = DeviceEventEmitter.addListener(
`hide_${this.props.id}`,
this.onSheetMangerHide
);
}
}
Example #21
Source File: App.tsx From tic-tac-toe-app with MIT License | 6 votes |
App: React.FC = () => {
useEffect(() => {
if (Platform.OS !== 'web') {
Sentry.init({
dsn: SENTRY_DSN,
enableInExpoDevelopment: false,
debug: process.env.NODE_ENV === 'development' ? true : false,
});
Sentry.setRelease(Constants.manifest.revisionId);
}
}, []);
const { store, persistor } = stores();
return (
<Provider store={store}>
<PersistGate loading={<AppLoading />} persistor={persistor}>
<View style={{ flex: 1 }}>
<StatusBar barStyle="light-content" />
{Platform.OS === 'web' ? (
<AppNavigatorWeb />
) : (
<AppNavigator />
)}
</View>
</PersistGate>
</Provider>
);
}
Example #22
Source File: SafeAreaView.tsx From sdc-ide with MIT License | 6 votes |
export function SafeAreaView(props: SafeAreaViewProps) {
const { style: originalStyle, drawBehind, children } = props;
const style = [s.safeAreaView, originalStyle];
if (drawBehind) {
return <View style={style}>{children}</View>;
}
return Platform.OS === 'ios' ? (
<RNSafeAreaView style={style}>{children}</RNSafeAreaView>
) : (
<View style={style}>{children}</View>
);
}
Example #23
Source File: registerForPushNotifications.ts From vsinder with Apache License 2.0 | 6 votes |
registerForPushNotifications = async () => {
if (Constants.isDevice) {
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
if (finalStatus !== "granted") {
return;
}
return (await Notifications.getExpoPushTokenAsync()).data;
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
}
Example #24
Source File: Header.tsx From BitcoinWalletMobile with MIT License | 6 votes |
Header: React.FC<Props> = (props) => {
const insets = useSafeAreaInsets()
const languageSelector = (state: WalletState) => state.language
const language = useSelector(languageSelector)
return (
<View style={styles.container}>
<View style={{ marginTop: insets.top, height: 56 }}>
{props.screen == getTranslated(language).getting_started &&
<TouchableOpacity onPress={props.action}>
<View style={styles.changeLanguageView}>
<Text style={styles.changeLanguageText}>{getTranslated(language).change_language}:</Text>
<View style={styles.currentLanguageView}><Text style={styles.currentLanguageText}>{props.currentLanguage}</Text></View>
</View>
</TouchableOpacity>
}
{props.screen != getTranslated(language).getting_started &&
<View style={styles.contentView}>
<TouchableOpacity disabled={Platform.OS == 'android'} onPress={props.action}>
<View style={styles.textContain}>
{Platform.OS == 'ios' && props.screen != getTranslated(language).receive && props.screen != getTranslated(language).settings &&
<Image style={styles.arrow} source={require('../assets/images/arrow.png')} />
}
<Text style={styles.headingText}>{props.screen}</Text>
</View>
</TouchableOpacity>
{(props.screen == getTranslated(language).create_new || props.screen == getTranslated(language).seed_phrase) &&
<View style={styles.stepContain}>
<Text style={styles.stepText}>Step </Text>
<Text style={styles.stepHightlight}>{props.screen == getTranslated(language).seed_phrase ? "2" : "1"}</Text><Text style={styles.stepText}>/2</Text>
</View>
}
</View>
}
</View>
</View>
);
}
Example #25
Source File: ReanimatedArcBase.tsx From reanimated-arc with MIT License | 6 votes |
render() {
const {diameter, width, color, style, lineCap} = this.props;
const offsetAndroid = Platform.OS === 'android' ? this.outerRadius : 0;
const pivot = this.outerRadius;
return (
<View style={style}>
<Svg
width={diameter}
height={diameter}
viewBox={`${-pivot} ${-pivot} ${diameter} ${diameter}`}>
<AnimatedG
style={{
transform: [
{translateX: -offsetAndroid},
{rotate: this.rotation},
{translateX: offsetAndroid},
],
}}>
<AnimatedPath
d={this.circlePath}
stroke={color}
strokeWidth={width}
strokeLinecap={lineCap}
fill="transparent"
transform={`translate(${-pivot} ${-pivot})`}
/>
</AnimatedG>
</Svg>
</View>
);
}
Example #26
Source File: Camera.tsx From SQUID with MIT License | 6 votes |
SelectImageButton = ({onSelectImage}) => {
if (!isImagePickerAvailable) {
return null
}
const ImagePicker = require('react-native-image-picker')
const options = {
...DEFAULT_OPTIONS,
title: 'Select Avatar',
};
const { showSpinner, hide } = useHUD()
return (
<TouchableOpacity
activeOpacity={0.8}
style={{ position: 'absolute', right: 0, padding: 16, alignSelf: 'center'}}
onPress={async () => {
showSpinner()
ImagePicker.launchImageLibrary(options, (response) => {
hide()
// console.log({ response })
if (Platform.OS == 'android' && "data" in response) {
const newFilePath = `${Date.now()}-tmp`
let tmpPath = `${RNFS.CachesDirectoryPath}/${newFilePath}`
RNFetchBlob.fs.writeFile(tmpPath, response.data, 'base64')
.then(() => {})
.finally(() => {
const uri = 'file://' + tmpPath
onSelectImage(uri)
})
} else {
const uri = response.uri
onSelectImage(uri)
}
});
}}
>
<EntypoIcon name="images" color="white" size={32} />
</TouchableOpacity>
)}
Example #27
Source File: AnimatedText.tsx From react-native-wagmi-charts with MIT License | 6 votes |
AnimatedText = ({ text, style }: AnimatedTextProps) => {
const inputRef = React.useRef<any>(null); // eslint-disable-line @typescript-eslint/no-explicit-any
if (Platform.OS === 'web') {
// For some reason, the worklet reaction evaluates upfront regardless of any
// conditionals within it, causing Android to crash upon the invokation of `setNativeProps`.
// We are going to break the rules of hooks here so it doesn't invoke `useAnimatedReaction`
// for platforms outside of the web.
// eslint-disable-next-line react-hooks/rules-of-hooks
useAnimatedReaction(
() => {
return text.value;
},
(data, prevData) => {
if (data !== prevData && inputRef.current) {
inputRef.current.value = data;
}
}
);
}
const animatedProps = useAnimatedProps(() => {
return {
text: text.value,
// Here we use any because the text prop is not available in the type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any;
});
return (
<AnimatedTextInput
underlineColorAndroid="transparent"
editable={false}
ref={Platform.select({ web: inputRef })}
value={text.value}
style={[styles.text, style]}
animatedProps={animatedProps}
/>
);
}
Example #28
Source File: BtnTemplate.tsx From ReactNative-UIKit with MIT License | 5 votes |
BtnTemplate: React.FC<BtnTemplateInterface> = (props) => {
const {disabled = false} = props;
const {styleProps} = useContext(PropsContext);
const {BtnTemplateStyles, theme, iconSize, customIcon} = styleProps || {};
const imageRef = React.useRef(null);
// This fixes the tint issue in safari browser
useImageDelay(imageRef, 10, '', props?.color || '');
return (
<TouchableOpacity
style={styleProps?.BtnTemplateContainer}
disabled={disabled}
onPress={props.onPress}>
<View
style={[
{...styles.controlBtn, ...(BtnTemplateStyles as object)},
props.style as object,
]}>
<Image
ref={Platform.OS === 'web' ? imageRef : undefined}
style={{
width: iconSize || 25,
height: iconSize || 25,
opacity: disabled ? 0.4 : 1,
tintColor: disabled ? 'grey' : props.color || theme || '#fff',
}}
resizeMode={'contain'}
source={{
uri: props.name
? customIcon?.[props.name]
? customIcon[props.name]
: icons[props.name]
: props.icon,
}}
/>
</View>
<Text
style={{
textAlign: 'center',
marginTop: 5,
color: disabled ? 'grey' : props.color || theme || '#fff',
opacity: disabled ? 0.4 : 1,
}}>
{props.btnText}
</Text>
</TouchableOpacity>
);
}
Example #29
Source File: App.tsx From react-native-detector with MIT License | 5 votes |
export default function App() {
const [screenshotCounter, setScreenshotCounter] = React.useState<number>(0);
React.useEffect(() => {
const requestPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
{
title: 'Get Read External Storage Access',
message:
'get read external storage access for detecting screenshots',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('You can use the READ_EXTERNAL_STORAGE');
} else {
console.log('READ_EXTERNAL_STORAGE permission denied');
}
} catch (err) {
console.warn(err);
}
};
if (Platform.OS === 'android') {
requestPermission();
}
const userDidScreenshot = () => {
setScreenshotCounter((screenshotCounter) => screenshotCounter + 1);
};
const unsubscribe = addScreenshotListener(userDidScreenshot);
return () => {
unsubscribe();
};
}, []);
return (
<View style={styles.container}>
<Text>User took {screenshotCounter} screenshot</Text>
</View>
);
}