react native share in a single application - react-native

In my react-native app, I want to share a text message with a specific application, e.g whatsapp or texting application without having to first land on the dialog with all the social applications.
For instance if I press the share button and whatsapp is called directly.
I tried using react-native-share but it seems to not be working anymore.

You can use Linking, which gives you a general interface to interact with both incoming and outgoing app links.
For example:
import React, { Component } from 'react';
import { Linking, Button } from 'react-native';
export class App extends Component {
render() {
return <Button
onPress={() => {
let url = 'whatsapp://send?text=Hola Mundo';
Linking.openURL(url).then((data) => {
console.log('open whatsapp')
}).catch(() => {
console.log('App not installed')
});
}}
title="Whatsapp"
color="#4FBE3C"/>;
}
}

For Android, the React Native Share module uses the default ACTION_SEND android intent:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
In order to have a different behavior, you need either write our own RN plugin that would talk to the app you want it to (if such feature is available) or find a similar plugin on npm.
I assume your plugin should do something like this:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);
sendIntent.setPackage("com.whatsapp");

Related

Launch url in default video player on android with react native

I found this native android code for what I am trying to achieve
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(newVideoPath), "video/mp4");
startActivity(intent);
(Android intent for playing video?)
But I can't figure out how to use apply it in react native with the Linking.sendIntent api, or if that api is even capable of doing it.
I also tried this module, but it failed to build the project with the error method does not override or implement a method from a supertype
I don't want to write a native module for this.
Turns out you can't send data with an intent with the built in sendIntent api, however there's a handy library that's capable of doing that (react-native-send-intent).
So now I am able to achieve what I wanted like so:
import { Linking, Platform } from "react-native";
import SendIntentAndroid from "react-native-send-intent";
export function playVideo(url){
var fn = Platform.select({
android(){
SendIntentAndroid.openAppWithData(
/* "org.videolan.vlc" */null,
"https://www.w3schools.com/html/mov_bbb.mp4",
"video/*"
).then(wasOpened => {});
},
default(){
Linking.openURL(url).catch(err => {});
}
});
fn();
}
Despite the library not offering a function for launching the default app for a url, you can achieve it by passing in null as the packagename, since the function it uses under the hood Intent.setPackage(String packageName), accepts null as a value.

WebXR not working in React Native WebView Component

How to make https://xr-spinosaurus.glitch.me/ work in a React Native WebView Component?
import React, { Component } from 'react';
import { WebView } from 'react-native';
export default class MyWeb extends Component {
render() {
return (
<WebView
source={{uri: 'https://xr-spinosaurus.glitch.me/'}}
style={{marginTop: 20}}
/>
);
}
}
Right now adding this to react-native only shows VR option but not AR option.
If you access the link directly you could see VR and AR options but I couldn't find the AR option when run in a Web View component inside React-Native
But the same AR option is available if I directly access the link on an ARCore supported Device.
How to make this code also show the AR option in React-Native?
AFAIK that is currently not possible, since the Android WebView doesn't (yet) support the WebXR Device API (and neither on apple). Source: https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API
I've been running into the same problem, hopefully support will be added soon, but for now there's not much you can do.

How to setup sendSignInLinkToEmail() from Firebase in react-native?

Working on a react-native project using #react-native-firebase/app v6 we recently integrated signing in with a "magic link" using auth.sendSignInLinkToEmail
We couldn't find a good example on how to setup everything in react-native and had different problems like
- auth/invalid-dynamic-link-domain - The provided dynamic link domain is not configured or authorized for the current project.
- auth/unauthorized-continue-uri - Domain not whitelisted by project
Searching for information and implementing the "magic link login" I've prepared a guide on how to have this setup in react-native
Firebase project configuration
Open the Firebase console
Prepare firebase instance (Email Link sign-in)
open the Auth section.
On the Sign in method tab, enable the Email/Password provider. Note that email/password sign-in must be enabled to use email link sign-in.
In the same section, enable Email link (passwordless sign-in) sign-in method.
On the Authorized domains tab (just bellow)
Add any domains that will be used
For example the domain for the url from ActionCodeSettings needs to be included here
Configuring Firebase Dynamic Links
For IOS - you need to have an ios app configured - Add an app or specify the following throughout the firebase console
Bundle ID
App Store ID
Apple Developer Team ID
For Android - you just need to have an Android app configured with a package name
Enable Firebase Dynamic Links - open the Dynamic Links section
“Firebase Auth uses Firebase Dynamic Links when sending a link that is meant to be opened in a mobile application.
In order to use this feature, Dynamic Links need to be configured in the Firebase Console.”
(ios only) You can verify that your Firebase project is properly configured to use Dynamic Links in your iOS app by opening
the following URL: https://your_dynamic_links_domain/apple-app-site-association
It should show something like:
{
"applinks": {
"apps": [],
"details": [
{
"appID": "AP_ID123.com.example.app",
"paths": [
"NOT /_/", "/"
]
}
]
}
}
IOS Xcode project configuration for universal links
Open the Xcode project and go to the Info tab create a new URL type to be used for Dynamic Links.
Enter a unique value in Identifier field and set the URL scheme field to be your bundle identifier, which is the default URL scheme used by Dynamic Links.
In the Capabilities tab, enable Associated Domains and add the following to the Associated Domains list: applinks:your_dynamic_links_domain
(!) This should be only the domain - no https:// prefix
Android
Android doesn’t need additional configuration for default or custom domains.
Packages
A working react-native project setup with react-native-firebase is required, this is thoroughly covered in the library own documentation, here are the specific packages we used
Note: using the dynamicLinks package can be replaced with react-native's own Linking module and the code would be almost identical
Exact packages used:
"#react-native-firebase/app": "^6.7.1",
"#react-native-firebase/auth": "^6.7.1",
"#react-native-firebase/dynamic-links": "^6.7.1",
Sending the link to the user email
The module provides a sendSignInLinkToEmail method which accepts an email and action code configuration.
Firebase sends an email with a magic link to the provided email. Following the link has different behavior depending on the action code configuration.
The example below demonstrates how you could setup such a flow within your own application:
EmailLinkSignIn.jsx
import React, { useState } from 'react';
import { Alert, AsyncStorage, Button, TextInput, View } from 'react-native';
import auth from '#react-native-firebase/auth';
const EmailLinkSignIn = () => {
const [email, setEmail] = useState('');
return (
<View>
<TextInput value={email} onChangeText={text => setEmail(text)} />
<Button title="Send login link" onPress={() => sendSignInLink(email)} />
</View>
);
};
const BUNDLE_ID = 'com.example.ios';
const sendSignInLink = async (email) => {
const actionCodeSettings = {
handleCodeInApp: true,
// URL must be whitelisted in the Firebase Console.
url: 'https://www.example.com/magic-link',
iOS: {
bundleId: BUNDLE_ID,
},
android: {
packageName: BUNDLE_ID,
installApp: true,
minimumVersion: '12',
},
};
// Save the email for latter usage
await AsyncStorage.setItem('emailForSignIn', email);
await auth().sendSignInLinkToEmail(email, actionCodeSettings);
Alert.alert(`Login link sent to ${email}`);
/* You can also show a prompt to open the user's mailbox using 'react-native-email-link'
* await openInbox({ title: `Login link sent to ${email}`, message: 'Open my mailbox' }); */
};
export default EmailLinkSignIn;
We're setting handleCodeInApp to true since we want the link from the email to open our app and be handled there. How to configure and handle this is described in the next section.
The url parameter in this case is a fallback in case the link is opened from a desktop or another device that does not
have the app installed - they will be redirected to the provided url and it is a required parameter. It's also required to
have that url's domain whitelisted from Firebase console - Authentication -> Sign in method
You can find more details on the supported options here: ActionCodeSettings
Handling the link inside the app
Native projects needs to be configured so that the app can be launched by an universal link as described
above
You can use the built in Linking API from react-native or the dynamicLinks #react-native-firebase/dynamic-links to intercept and handle the link inside your app
EmailLinkHandler.jsx
import React, { useState, useEffect } from 'react';
import { ActivityIndicator, AsyncStorage, StyleSheet, Text, View } from 'react-native';
import auth from '#react-native-firebase/auth';
import dynamicLinks from '#react-native-firebase/dynamic-links';
const EmailLinkHandler = () => {
const { loading, error } = useEmailLinkEffect();
// Show an overlay with a loading indicator while the email link is processed
if (loading || error) {
return (
<View style={styles.container}>
{Boolean(error) && <Text>{error.message}</Text>}
{loading && <ActivityIndicator />}
</View>
);
}
// Hide otherwise. Or show some content if you are using this as a separate screen
return null;
};
const useEmailLinkEffect = () => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const handleDynamicLink = async (link) => {
// Check and handle if the link is a email login link
if (auth().isSignInWithEmailLink(link.url)) {
setLoading(true);
try {
// use the email we saved earlier
const email = await AsyncStorage.getItem('emailForSignIn');
await auth().signInWithEmailLink(email, link.url);
/* You can now navigate to your initial authenticated screen
You can also parse the `link.url` and use the `continueurl` param to go to another screen
The `continueurl` would be the `url` passed to the action code settings */
}
catch (e) {
setError(e);
}
finally {
setLoading(false);
}
}
};
const unsubscribe = dynamicLinks().onLink(handleDynamicLink);
/* When the app is not running and is launched by a magic link the `onLink`
method won't fire, we can handle the app being launched by a magic link like this */
dynamicLinks().getInitialLink()
.then(link => link && handleDynamicLink(link));
// When the component is unmounted, remove the listener
return () => unsubscribe();
}, []);
return { error, loading };
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFill,
backgroundColor: 'rgba(250,250,250,0.33)',
justifyContent: 'center',
alignItems: 'center',
},
});
const App = () => (
<View>
<EmailLinkHandler />
<AppScreens />
</View>
);
You can use the component in the root of your app as in this example
Or you can use it as a separate screen/route - in that case the user should be redirected to it after
the sendSignInLinkToEmail action
Upon successful sign-in, any onAuthStateChanged listeners will trigger with the new authentication state of the user. The result from the signInWithEmailLink can also be used to retrieve information about the user that signed in
Testing the email login link in the simulator
Have the app installed on the running simulator
Go through the flow that will send the magic link to the email
Go to your inbox and copy the link address
Open a terminal and paste the following code
xcrun simctl openurl booted {paste_the_link_here}
This will start the app if it’s not running
It will trigger the onLink hook (if you have a listener for it like above)
References
Deep Linking In React Native Using Firebase Dynamic Links
React Native Firebase - Dynamic Links
React Native Firebase - auth - signInWithEmailLink
firebase.google.com - Passing State In Email Actions
firebase.google.com - Authenticate with Firebase Using Email Link in JavaScript

How do I render a Shoutem extension

I was wondering how I would render some Shoutem extension, for simplicity I am going to render it as my only component like so:
import 'es6-symbol/implement';
import React from 'react';
import {
AppRegistry,
View
} from 'react-native';
import { AppBuilder } from '#shoutem/core';
import { NavigationBar } from '#shoutem/ui';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import extensions from './extensions.js';
import { screens } from './extensions/kevinyclu.restaurants/app/index';
const List = screens.List;
const store = createStore((state, action) => state);
const App = () => <Provider store={store}><View><List /></View></ Provider>;
// noinspection JSCheckFunctionSignatures
AppRegistry.registerComponent('Restaurant', () => App);
But this gives me an error that says:
Though if I replace the const App = ... with the code that was initially there when I did shoutem configure
const App = new AppBuilder()
.setExtensions(extensions)
.setRenderNavigationBar(renderNavigationBar)
.build();
Then everything works fine, so I was wondering how would I use a Shoutem extension? Or am I missing the point of the extension completely?
You simply add it in the Builder by adding a screen. The flow is explained in our getting started docs. You create an extension, create a screen with a shortcut and then upload it to the Shoutem servers and install it in one of your apps on the Builder.
After that, you can go to the app in the Builder and add that new extension's screen by clicking the + button next to Screens. You can easily find your new extension by selecting the Custom category.
Remember that after installing a new app, you should run shoutem configure in the cloned app's directory. This will set up the new configuration you have after you've installed a new extension on the Builder.
Some advice; if you ever uninstall an extension on the Builder, it's good to re-clone your app completely, because shoutem configure will not remove the extension's from the directory, which may "hide" errors. For example, you could be importing something from that extension that you uninstalled, but you won't get an error because the files are all still there, even though they're uninstalled.

How To Use both 'adjustPan' and 'adjustResize' for 'windowSoftInputMode' in React Native Android app

How can I use both 'adjustPan' and 'adjustResize' in AndroidManifest.xml react native app.
Use Case
My navigation is made upon ReactNavigation with StackNavigator and TabNavigator. I have a text box where the user can type any data. While performing this, the tab bar is displaying on the top of Keyboard. In order to block this i used 'adjustPan' and it worked fine.
On another screen, I have a registration with multiple text boxes. Here I cant scroll the entire screen unless and clicking 'tick' on the keyboard or manually click system back button. To solve this issue I found 'KeyboardAvoidingView' which is working fine. but to activate this need to change 'windowSoftInputMode' to 'adjustResize'.
In documentation, found that these two have entirely different property and I can't both together. could someone help me on this?
References:https://medium.freecodecamp.org/how-to-make-your-react-native-app-respond-gracefully-when-the-keyboard-pops-up-7442c1535580
I found an npm package called react-native-android-keyboard-adjust, which allows us to switch the windowSoftInputMode on demand, this should be able to cater for your use case. However, the library seems to be not actively maintained and the installation documentation is a little bit out of date but for the most part, you can follow the instructions given by the README.md.
For the Update MainActivity.java in your project part, the recent versions of React Native should be able to auto-link the dependencies and there is no need to do this modification manually.
After the above steps, you can try to start your app. If you encountered an error related to something like The number of method references in a .dex file cannot exceed 64k, you can add the followings to your android/app/build.gradle file
android {
...
defaultConfig {
...
multiDexEnabled true
}
...
}
After installing the package, you can call the methods provided by the library to change the windowSoftInputMode as you need.
For example, assuming you have a default windowSoftInputMode of adjustResize, and you want to use adjustPan within ScreenA, you can call AndroidKeyboardAdjust.setAdjustPan() when ScreenA mount, and reset the windowSoftInputMode to adjustResize on unmount by calling AndroidKeyboardAdjust.setAdjustResize()
As of 2023, the best choice is react-native-avoid-softinput. react-native-android-keyboard-adjust isn't supported anymore.
You can use AvoidSoftInput.setAdjustPan and AvoidSoftInput.setAdjustResize.
I use custom hook to disable my default behavior on some screens.
import { useCallback } from 'react'
import { AvoidSoftInput } from 'react-native-avoid-softinput'
import { useFocusEffect } from '#react-navigation/native'
import { Platform } from 'react-native'
function useAndroidKeyboardAdjustNothing() {
useFocusEffect(
useCallback(() => {
if (Platform.OS === 'android') {
AvoidSoftInput.setAdjustNothing()
AvoidSoftInput.setEnabled(true)
}
return () => {
if (Platform.OS === 'android') {
AvoidSoftInput.setEnabled(false)
AvoidSoftInput.setAdjustResize()
}
}
}, []),
)
}