React Native sharing content - react-native

I am trying to learn the basics of react native and have started with the basic tab template. I am trying to create a social media sharing screen, where you get the list of apps and airdrop on iOS to display but unfortunately this is not working. The code I have displays an empty view and I was expecting the share dialog to appear over the top. I get the view but no sharing options.
Here is the code
`
import React from 'react';
import { View, StyleSheet } from 'react-native';
import { Share } from 'react-native';
var ActionSheetIOS = React;
export default class ShareScreen extends React.Component {
static navigationOptions = {
title: 'Share',
};
showShareActionSheet() {
ActionSheetIOS.showShareActionSheetWithOptions({
url: 'https://www.someurl.org',
});
}
render() {
return (
<View style={styles.container}>
this.showShareActionSheet();
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 15,
backgroundColor: '#000000',
},
});
`
any ideas why this isn't working?

You need to wrap your this.showShareActionSheet(); with brackets to get it working.
<View style={styles.container}>
{this.showShareActionSheet()}
</View>
Otherwise it's gonna be considered as plain text and not as an instruction

You can use this package https://www.npmjs.com/package/react-native-share for sharing, This package will help you share the content to WhatsApp, FB, and other social apps.

Related

How to share an image to Instagram Stories from Expo / React Native

How do I share an image directly to an Instagram story using Expo / React Native?
This issue has already been solved for iOS for normal Instagram posts, but not stories.
Facebook's docs explain how to do this for iOS and Android, but not React Native.
Expected behavior:
Open Instagram story with the selected image.
Current behavior:
Opens Instagram story with blank screen.
The problem I'm facing:
I'm not quite sure how to generate a URI that fits Instagram's schema, as referenced in their docs.
Reproducible Snack
https://snack.expo.io/#nandorojo/share-to-instagram-story
Thank you so much!
Here is my code from the snack above:
import * as React from 'react';
import { Text, View, StyleSheet, Linking, Image } from 'react-native';
import * as FileSystem from 'expo-file-system';
const url = 'https://source.unsplash.com/daily';
export default class App extends React.Component {
_shareToStory = async () => {
// download to device
const { uri } = await FileSystem.downloadAsync(
url,
`${FileSystem.documentDirectory}meme.jpg`
).catch(e => console.log('instagram share failed', JSON.stringify(e), url));
try {
const encodedUrl = encodeURIComponent(uri);
const instagramUrl = `instagram-stories://share?backgroundImage=${encodedUrl}`;
Linking.openURL(instagramUrl);
} catch (error) {
console.log(error);
}
};
render() {
return (
<View style={styles.container}>
<Image source={{ uri: url }} style={{ height: 100, width: 100 }} />
<Text style={styles.paragraph} onPress={this._shareToStory}>
Share to Instagram Story
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
If you're using Expo Managed Workflow, your options are very limited. As of SDK v38, afaik it's only possible to accomplish this on Android, and only if you're sharing a background image (due to missing Expo APIs for content permissions and pasteboard), then something like this might work:
import * as FileSystem from 'expo-file-system'
import * as IntentLaucher from 'expo-intent-launcher'
// url of the file to share
const url = '....'
// some random temporary filename
const localFile = `${FileSystem.cacheDirectory}${uuid()}.jpg`
try {
FileSystem.downloadAsync(url, localFile)
.then(({ uri }) => {
FileSystem.getContentUriAsync(uri).then(contentUri => {
IntentLauncher.startActivityAsync(
'com.instagram.share.ADD_TO_STORY',
{
data: contentUri,
flags: 1, // FLAG_GRANT_READ_URI_PERMISSION
type: 'image/jpeg', // or other based on your file type
}
).catch(console.warn)
})
})
.catch(console.warn)
} finally {
FileSystem.deleteAsync(localFile).catch(console.warn)
}
However, if you're using React Native (or have ejected to Expo Bare Workflow), then you have more options. I'd recommend using the RN community supported react-native-share library that works on both Android and iOS and supports all of the sharing options (plus many other services):
import Share from 'react-native-share'
Share.shareSingle({
method: Share.InstagramStories.SHARE_BACKGROUND_IMAGE,
backgroundImage: '....' // url of the file to share
social: Share.Social.INSTAGRAM_STORIES,
})

React Native: no style on views works when I use react-router / react-router-navigation

Advance, sorry if my english is not the best.
I've not been working on React Native for a very long time and now I have to implement an app with it. I currently use:
Android Studio 3.3
Android 9.0 Api 28
React Native 0.57.8
React Router 4.3.1
React Router Native 4.3.0
React Router Navigation 2.0.0-alpha.10
By the time I added the router, the styles worked like backgroundColor. Since then, the background of the app is only white and no matter which component I can't e.g. do represent a border when I use a view.
Have I might have missed something?
I have already tested the View element at every point. Same result. As I said, before I used React Router, it worked. With the integration of React Native Paper and Redux, there were no problems. I also tried customizing the styles.xml. Although this does work for permanently changing the background color, that's why I still can not put Border in any component. I also tried "component" instead of "render" in the Card component. And also with its own layout component.
App.js
import React from 'react'
import { StyleSheet, View } from 'react-native'
import { Provider as StoreProvider } from 'react-redux'
import { createStore } from 'redux'
import reducers from './reducers'
import { NativeRouter } from 'react-router-native'
import { Navigation, Card } from 'react-router-navigation'
import { Provider as PaperProvider } from 'react-native-paper'
import theme from './assets/js/theme'
import { Login } from './components/Views'
const appStyles = StyleSheet.create({
root: {
backgroundColor: theme.colors.background
}
})
export default App = () => {
return (
<View styles={ appStyles.root }>
<StoreProvider store={createStore(reducers)}>
<PaperProvider theme={theme}>
<NativeRouter>
<Navigation hideNavBar>
<Card
exact
path="/"
render={() => <Login/>}
/>
</Navigation>
</NativeRouter>
</PaperProvider>
</StoreProvider>
</View>
)
}
part of Login.js
const loginStyles = StyleSheet.create({
login: {
width: 400,
height: 400,
borderWidth: 4,
borderColor: theme.colors.error,
borderRadius: 3,
padding: 20,
justifyContent: 'center'
}
})
class Login extends Component {
render() {
console.log('LOGIN')
return (
<View styles={loginStyles.login}>
<Text style={{ color: theme.colors.error, alignSelf: 'center' }}>Test</Text>
</View>
)
}
}
None of it worked. Thanks for help.
I solved it myself. I am now using React Native Router Flux. I am still learning and trying out.

How to change uri value of Video component dynamically

I am working with react native, and I am using a video component from the expo. during this how I can change the value for URI attribute dynamically
(As you mentioned in the comment that you already solved the problem and want to play youtube videos)
You can use WebView to play Youtube video.
Working demo: https://snack.expo.io/Syhzx-VvX
Here is the sample code:
import React, { Component } from 'react';
import { StyleSheet, View, WebView, Platform } from 'react-native';
export default class App extends Component<{}> {
render() {
return (
<View style={{ height: 300 }}>
<WebView
style={ styles.WebViewContainer }
javaScriptEnabled={true}
domStorageEnabled={true}
source={{uri: 'https://www.youtube.com/embed/YE7VzlLtp-4' }}
/>
</View>
);
}
}
const styles = StyleSheet.create({
WebViewContainer: {
marginTop: (Platform.OS == 'android') ? 20 : 0,
}
});
Otherwise if you don't want to use WebView, use a third party package like react-native-youtube

React-Native not displaying background Image

I'm trying to set a background Image in React-Native but it is not appearing on my screen. However, the text inside <ImageBackground></ImageBackground> is getting displayed.
Here's my code:
import React, { Component } from 'react';
import { View, ImageBackground, Text, StyleSheet } from 'react-native';
type Props = {};
export default class App extends Component {
render() {
return (
<ImageBackground style={styles.container} source={require("./Assets/bg.png")}>
<Text>Inside</Text>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
width: '100%',
height: '100%'
}
});
Here is my directory structure below. You can see there bg.png exists.
And Here is the output that I'm getting.
Here is my bg.png
I can't find what's wrong with this. Everything seems ok, Also I'm not getting any error message. Please Help
Here's the link to the expo.
It appears that there happens a crash in android for large images the bitmap becomes out of memory.
Therefore a workaround for that is to resize the image and use it.
For more info checkout this link

React Native Camera Roll

Haven't noticed much sample code/guides on how to use the CameraRoll library from React Native, I found the example in the docs a bit "vague" and confusing.
First time I'm using any of the API's so I do not fully understand how I'm suppose to use the library either. So far I've imported it like:
import {
AppRegistry,
Image,
StyleSheet,
TextInput,
Navigator,
CameraRoll,
Alert,
TouchableHighlight,
Button,
Text,
View
} from 'react-native';
quite confused with "Linking" etc, but as far as I know, this should be all I need to do in order to use the lib.
And how do I use it for something as simple as to open the gallery on the click of a button and let the user choose an image that should then be displayed in the app.
Thanks in advance, hope someone has some code to clarify this.
Here is some sample code that will grab the first 25 photos from your camera roll and display them in a ScrollView. I modified this from an example I found online here
import React, { Component, PropTypes } from 'react'
import {
CameraRoll,
Image,
ScrollView,
StyleSheet,
TouchableHighlight,
View,
} from 'react-native';
class CameraRollView extends Component {
constructor(props) {
super(props)
var controls = props.controls
this.state = {
images: [],
selected: '',
fetchParams: { first: 25 },
groupTypes: 'SavedPhotos',
}
this._storeImages = this._storeImages.bind(this)
this._logImageError = this._logImageError.bind(this)
this._selectImage = this._selectImage.bind(this)
}
componentDidMount() {
// get photos from camera roll
CameraRoll.getPhotos(this.state.fetchParams, this._storeImages, this._logImageError);
}
// callback which processes received images from camera roll and stores them in an array
_storeImages(data) {
const assets = data.edges;
const images = assets.map( asset => asset.node.image );
this.setState({
images: images,
});
}
_logImageError(err) {
console.log(err);
}
_selectImage(uri) {
// define whatever you want to happen when an image is selected here
this.setState({
selected: uri,
});
console.log('Selected image: ', uri);
}
render() {
return (
<View style={{flex: 1, backgroundColor: 'white'}}>
<ScrollView style={styles.container}>
<View style={styles.imageGrid}>
{ this.state.images.map(image => {
return (
<TouchableHighlight onPress={() => this._selectImage(image.uri)}>
<Image style={styles.image} source={{ uri: image.uri }} />
</TouchableHighlight>
);
})}
</View>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
imageGrid: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center'
},
image: {
width: 100,
height: 100,
margin: 10,
},
});
export default CameraRollView
Hmm, the package you are seeking is probably react-native-image-picker. It allows you to take a photo or select one from your native device gallery.
LINK: https://github.com/react-community/react-native-image-picker
In response to the linking issue. When you save a package using:
npm install --save react-native-image-picker
What is happening here is the --save part prepares the packages dependencies to be connected to native iOS and Android. This linking is done using the command react-native link.
In some cases packages require some manual linking aswell (for example, this package requires a small amount of native iOS and Android configuration)