react-native#Share TypeScript Examples
The following examples show how to use
react-native#Share.
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: community.tsx From protect-scotland with Apache License 2.0 | 6 votes |
shareApp = async (t: TFunction) => {
const url = t('links:l');
try {
await Share.share(
{
title: t('common:shareMessage'),
message: Platform.OS === 'android' ? url : undefined,
url
},
{
subject: t('common:name'),
dialogTitle: t('common:name')
}
);
} catch (error) {}
}
Example #2
Source File: Header.spec.tsx From react-native-network-logger with MIT License | 6 votes |
test('share button renders when provided with value', async () => {
const { getByTestId } = render(
<Header shareContent="share me">My Title</Header>
);
expect(getByTestId('header-text').props.children).toEqual('My Title');
expect(getByTestId('header-share')).toBeDefined();
act(() => {
fireEvent.press(getByTestId('header-share'));
});
expect(Share.share).toHaveBeenCalledWith({ message: 'share me' });
});
Example #3
Source File: Header.tsx From react-native-network-logger with MIT License | 6 votes |
Header: React.FC<Props> = ({ children, shareContent }) => {
const styles = useThemedStyles(themedStyles);
return (
<View style={styles.container}>
<Text
style={styles.header}
accessibilityRole="header"
testID="header-text"
>
{children}
</Text>
{!!shareContent && (
<TouchableOpacity
testID="header-share"
accessibilityLabel="Share"
accessibilityRole="button"
onPress={() => {
Share.share({ message: shareContent });
}}
>
<Image
source={require('./share.png')}
resizeMode="contain"
style={styles.shareIcon}
/>
</TouchableOpacity>
)}
</View>
);
}
Example #4
Source File: RequestDetails.tsx From react-native-network-logger with MIT License | 5 votes |
RequestDetails: React.FC<Props> = ({ request, onClose }) => {
const [responseBody, setResponseBody] = useState('Loading...');
const styles = useThemedStyles(themedStyles);
useEffect(() => {
(async () => {
const body = await request.getResponseBody();
setResponseBody(body);
})();
}, [request]);
const requestBody = request.getRequestBody(!!request.gqlOperation);
const getFullRequest = () => {
let response;
if (responseBody) {
try {
response = JSON.parse(responseBody);
} catch {
response = `${responseBody}`;
}
}
const processedRequest = {
...request,
response,
duration: request.duration,
};
return JSON.stringify(processedRequest, null, 2);
};
return (
<View style={styles.container}>
<ResultItem request={request} style={styles.info} />
<ScrollView style={styles.scrollView} nestedScrollEnabled>
<Headers title="Request Headers" headers={request.requestHeaders} />
<Header shareContent={requestBody}>Request Body</Header>
<LargeText>{requestBody}</LargeText>
<Headers title="Response Headers" headers={request.responseHeaders} />
<Header shareContent={responseBody}>Response Body</Header>
<LargeText>{responseBody}</LargeText>
<Header>More</Header>
<Button
onPress={() => Share.share({ message: getFullRequest() })}
fullWidth
>
Share full request
</Button>
<Button
onPress={() => Share.share({ message: request.curlRequest })}
fullWidth
>
Share as cURL
</Button>
</ScrollView>
{!backHandlerSet() && (
<Button onPress={onClose} style={styles.close}>
Close
</Button>
)}
</View>
);
}
Example #5
Source File: ScanHomeHeader.tsx From hamagen-react-native with MIT License | 4 votes |
ScanHomeHeader: FunctionComponent<ScanHomeHeaderProps> = ({ isRTL, languages, locale, externalUrls, strings: { scanHome: { share: { message, title, androidTitle } } }, openDrawer, enableBle }) => {
const messageAndUrl = useMemo(() => {
const relevantLocale: string = Object.keys(languages.short).includes(locale) ? locale : 'he';
return `${message}\n${externalUrls?.shareMessage?.[relevantLocale] ?? ''}`;
}, [locale]);
const [showDot, setShowDot] = useState(false);
const showBLEBtn: string = useMemo(() => {
switch (enableBle) {
case 'false':
return 'empty';
case 'true':
return 'full';
case 'blocked':
case null:
default:
return 'hide';
}
}, [enableBle]);
useEffect(() => {
init();
}, []);
const init = async () => {
try {
const res = await AsyncStorage.getItem(MENU_DOT_LAST_SEEN);
if (res) {
if (parseInt(res, 10) < SHOW_DOT_BY_BUILD_NUMBER) {
setShowDot(true);
} else {
setShowDot(false);
}
} else {
setShowDot(true);
}
} catch {
setShowDot(true);
}
};
const onShare = async () => {
try {
await Share.share({ message: messageAndUrl, title }, { dialogTitle: androidTitle, subject: title });
} catch (error) {
onError({ error });
}
};
return (
<ImageBackground
source={require('../../assets/main/headerBG.png')}
style={styles.imageContainer}
resizeMode="stretch"
resizeMethod="resize"
>
<View style={[styles.container, { flexDirection: isRTL ? 'row-reverse' : 'row' }]}>
<TouchableOpacity
hitSlop={HIT_SLOP}
onPress={() => {
openDrawer();
showDot && setShowDot(false);
AsyncStorage.setItem(MENU_DOT_LAST_SEEN, VERSION_BUILD);
}}
>
<Icon source={showDot ? require('../../assets/main/menuWithDot.png') : require('../../assets/main/menu.png')} width={20} />
</TouchableOpacity>
<View style={styles.logoContainer}>
<Icon source={require('../../assets/main/headerLogo.png')} width={89} height={43} />
</View>
<View style={{ flexDirection: isRTL ? 'row-reverse' : 'row' }}>
{showBLEBtn !== 'hide' && (
<TouchableOpacity style={{ marginHorizontal: 20 }} hitSlop={HIT_SLOP} onPress={() => toggleBLEService(showBLEBtn !== 'full')}>
<Icon source={showBLEBtn === 'full' ? require('../../assets/main/bluetoothOnBtn.png') : require('../../assets/main/bluetoothOffBtn.png')} width={23} />
</TouchableOpacity>
)}
<TouchableOpacity hitSlop={HIT_SLOP} onPress={onShare}>
<Icon source={require('../../assets/main/share.png')} width={20} />
</TouchableOpacity>
</View>
</View>
<View style={styles.bottomEdge} />
</ImageBackground>
);
}
Example #6
Source File: index.tsx From hive-keychain-mobile with MIT License | 4 votes |
UrlModal = ({
isVisible,
toggle,
onNewSearch,
url,
setUrl,
history,
clearHistory,
}: Props) => {
const urlInput: MutableRefObject<TextInput> = useRef();
const insets = useSafeAreaInsets();
const styles = getStyles(insets);
if (isVisible && urlInput) {
setTimeout(() => {
const {current} = urlInput;
if (current && !current.isFocused()) {
current.focus();
}
}, SLIDE_TIME);
}
const onSubmitUrlFromInput = (
obj: NativeSyntheticEvent<TextInputSubmitEditingEventData>,
) => {
const url = obj.nativeEvent.text;
onSubmitUrl(url);
};
const onSubmitUrl = (url: string) => {
toggle(false);
// Add duckduck go search for url with no domain
if (url.includes(' ') || !url.includes('.')) {
onNewSearch(`https://duckduckgo.com/?q=${url.replace(/ /g, '+')}`);
} else {
const hasProtocol = url.match(/^[a-z]*:\/\//);
const sanitizedURL = hasProtocol ? url : `https://${url}`;
onNewSearch(sanitizedURL);
}
};
const dismissModal = () => {
toggle(false);
};
return (
<Modal
isVisible={isVisible}
style={styles.urlModal}
onBackdropPress={dismissModal}
onBackButtonPress={dismissModal}
animationIn="slideInDown"
animationOut="slideOutUp"
backdropOpacity={0.8}
animationInTiming={SLIDE_TIME}
animationOutTiming={SLIDE_TIME}
useNativeDriver>
<View style={styles.urlModalContent}>
<TextInput
keyboardType="web-search"
ref={urlInput}
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="never"
onChangeText={setUrl}
onSubmitEditing={onSubmitUrlFromInput}
placeholder={translate('browser.search')}
returnKeyType="go"
style={styles.urlInput}
value={url}
selectTextOnFocus
/>
{url.length ? (
<TouchableOpacity
style={styles.option}
onPress={() => Share.share({message: url})}>
<ShareIcon width={16} height={16} />
</TouchableOpacity>
) : null}
{url.length ? (
<TouchableOpacity
style={styles.option}
onPress={() => Clipboard.setString(url)}>
<Copy width={16} height={16} />
</TouchableOpacity>
) : null}
{url.length ? (
<TouchableOpacity style={styles.option} onPress={() => setUrl('')}>
<Text style={styles.eraseText}>X</Text>
</TouchableOpacity>
) : null}
</View>
<ScrollView>
<UrlAutocomplete onSubmit={onSubmitUrl} input={url} history={history} />
{history.length ? (
<TouchableOpacity onPress={clearHistory}>
<Text style={styles.clearHistory}>
{translate('browser.history.clear')}
</Text>
</TouchableOpacity>
) : null}
</ScrollView>
</Modal>
);
}
Example #7
Source File: BottomActionBar.tsx From sellflow with MIT License | 4 votes |
export default function BottomActionBar(props: Props) {
let { addToWishlist } = useAddItemToWishlist();
let { removeFromWishlist } = useRemoveItemFromWishlist();
let {
isWishlistActive,
onWishlistPress,
onAddToCartPress,
product,
isLoading,
isButtonDisabled,
} = props;
let { data: shopData } = useQuery<GetShop>(GET_SHOP);
let shareMessage = shopData
? t('Check out this product from {shopName}', {
shopName: shopData.shop.name,
})
: t('Check out this product');
let onPressWishlist = () => {
onWishlistPress(!isWishlistActive);
if (isWishlistActive === false) {
addToWishlist({ variables: { product } });
} else {
removeFromWishlist({ variables: { productHandle: product.handle } });
}
};
let onShare = () => {
Share.share({
message: `${shareMessage}: ${product.title} ${product.url}`,
});
};
let buttonLabel = () => {
if (isLoading) {
return null;
}
if (!product.id) {
return t('Unavailable');
}
if (product.availableForSale) {
return t('Add to Cart');
}
return t('Out of Stock');
};
let addButtonAction = !isLoading ? onAddToCartPress : () => {};
return (
<View style={styles.bottomIconContainer}>
<IconButton
icon="share-variant"
color={COLORS.primaryColor}
onPress={onShare}
style={styles.icon}
/>
{isWishlistActive ? (
<IconButton
icon="heart"
color={COLORS.wishlist}
onPress={onPressWishlist}
style={styles.icon}
/>
) : (
<IconButton
icon="heart-outline"
onPress={onPressWishlist}
style={styles.icon}
/>
)}
<Button
style={[
defaultButton,
styles.flex,
isButtonDisabled && styles.disabledButton,
]}
labelStyle={[
defaultButtonLabel,
isButtonDisabled && styles.disabledLabel,
]}
disabled={isButtonDisabled}
loading={isLoading}
onPress={addButtonAction}
>
{buttonLabel()}
</Button>
</View>
);
}
Example #8
Source File: referral-screen.tsx From beancount-mobile with MIT License | 4 votes |
ReferralScreen = connect(
(state: { base: { userId: string } }) => ({ userId: state.base.userId })
)(function ReferralScreen(props: Props): JSX.Element {
React.useEffect(() => {
async function init() {
await analytics.track("page_view_referral", {});
}
init();
}, []);
const { userId } = props;
const shareLink = `beancount.io/sign-up/?src=${Platform.OS}&by=${userId}`;
const theme = useTheme().colorTheme;
const styles = getStyles(theme);
return (
<View style={styles.container}>
<NavigationBar
title={i18n.t("referral")}
showBack
navigation={props.navigation}
/>
<View style={styles.body}>
<CommonMargin />
<CommonMargin />
<ReferralGiftIcon />
<CommonMargin />
<Text style={styles.title}>{i18n.t("rewardSummary")}</Text>
<CommonMargin />
<Text style={styles.summary}>{i18n.t("rewardDetail")}</Text>
<CommonMargin />
<CommonMargin />
<View style={styles.shareLinkContainer}>
<Text numberOfLines={1} style={styles.shareLink}>
{shareLink}
</Text>
<TouchableOpacity
style={styles.copyBtn}
onPress={async () => {
Clipboard.setString(shareLink);
Toast.show(i18n.t("copied"), 1);
await analytics.track("tap_share_link_copy", { shareLink });
}}
>
<Text style={styles.copy}>{i18n.t("copy")}</Text>
</TouchableOpacity>
</View>
<View style={{ flex: 1 }}></View>
<Button
style={styles.inviteBtn}
onPress={async () => {
await analytics.track("tap_navigate_to_invite", { shareLink });
props.navigation.navigate("Invite", { shareLink });
}}
>
<Text style={styles.invite}>{i18n.t("inviteFromContacts")}</Text>
</Button>
<CommonMargin />
<Button
style={styles.shareBtn}
onPress={async () => {
await analytics.track("tap_share_link_share", { shareLink });
Share.share({
message: `${i18n.t("recommend")} ${shareLink}`,
})
.then((result) => {
if (result.action === Share.sharedAction) {
if (result.activityType) {
// shared with activity type of result.activityType
} else {
// shared
}
} else if (result.action === Share.dismissedAction) {
// dismissed
}
})
.catch((_) => {
Toast.fail(i18n.t("shareError"));
});
}}
>
<Text style={styles.share}>{i18n.t("share")}</Text>
</Button>
<CommonMargin />
</View>
</View>
);
})