How React Native to control Play/Pause Video in WebView - react-native

I am trying to play and pause video in WebView by React Native.
But when this.state.shouldPlay becomes true, the below injectedJavaScript does not work.
injectedJavaScript=
{`document.getElementsByTagName("video")[0].play();`}
Please advise how to control Video in WebView from React Native.
react-native-video cannot be used because of performance issue.
import * as React from 'react';
import { Component, useState, useEffect } from 'react';
import { Text, View, StyleSheet, Image, TouchableOpacity} from 'react-native';
import {WebView} from 'react-native-webview';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
shouldPlay: false, // not play at default
}
}
_handlePlayAndPause = () => {
if (this.state.shouldPlay == false) {
this.setState({shouldPlay: true });
} else {
this.setState({shouldPlay: false });
};
render() {
const {shouldPlay } = this.state;
return (
<View style={styles.container}>
{ shouldPlay ?
<View>
<WebView
source={{ uri: www.url.com/sample.mp4 }}
javaScriptEnabled = {true}
injectedJavaScript=
{`document.getElementsByTagName("video")[0].play();`}
/>
</View>
:
<View>
<WebView
source={{ uri: www.url.com/sample.mp4 }}
javaScriptEnabled = {true}
injectedJavaScript=
{`document.getElementsByTagName("video")[0].pause();`}
/>
</View>
}
{ shouldPlay ?
<View>
<TouchableOpacity onPress={ this._handlePlayAndPause } >
<Ionicons name="ios-pause"/>
</TouchableOpacity>
</View>
:
<View>
<TouchableOpacity onPress={ this._handlePlayAndPause } >
<Ionicons name="ios-play-circle"/>
</TouchableOpacity>
</View>
}
</View>
)
}
}
Thank you.

Related

react native I want to designate one image as the default

I wrote the code to upload an image, but when I click remove image, a blue screen appears as a default. I want to designate this screen as one image.
import 'react-native-gesture-handler'
import * as React from 'react';
import{
StyleSheet,
View,
Text,
Image,
TouchableOpacity,
ToastAndroid,
Alert,
} from 'react-native';
import { Avatar } from 'react-native-paper';
import { launchImageLibrary } from 'react-native-image-picker';
import styled from 'styled-components';
const Container = styled.SafeAreaView`
flex : 1;
`;
export default function Profile(){
const [pic, Setpic] = React.useState('');
const setToastMsg = msg => {
ToastAndroid.showWithGravity(msg, ToastAndroid.SHORT, ToastAndroid.CENTER)
};
const uploadImage = () => {
let options = {
mediaType : 'photo',
quality : 1,
includeBase64 : true,
};
launchImageLibrary(options, response => {
if(response.didCancel){
setToastMsg('Cancelled image selection');
}
else if((response.errorCode == 'permission')){
setToastMsg('permision not satisfied');
}
else if((response.errorCode == 'others')){
setToastMsg(response.errorMessage);
}
else if(response.assets[0].fileSize > 2097152){
Alert.alert(
'Maximum image size exceeded',
'Please choose image under 2MB'
[{text: 'OK'}],
);
}
else{
Setpic(response.assets[0].base64);
}
});
}
const removeImage = () => {
Setpic('');
setToastMsg('Image removed');
}
return(
<Container>
<View>
<Avatar.Image
size= {150}
source={{ uri : 'data:image/png;base64,' + pic}}
/>
</View>
<View>
<TouchableOpacity activeOpacity={0.5} onPress={ ()=> uploadImage() }>
<Text>
Upload Image
</Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity={0.5} onPress={ ()=> removeImage() }>
<Text>
Remove Image
</Text>
</TouchableOpacity>
</View>
</Container>
);
}
Can I change the code here?
const removeImage = () => {
Setpic('');
setToastMsg('Image removed');
}
or here?
<View>
<Avatar.Image
size= {150}
source={{ uri : 'data:image/png;base64,' + pic}}
/>
</View>
I'm curious where you set the default image.
If you can't change the default image, please help me to change the color.
This code is based on Android
you could try a condition if pic is empty or not.
If it is empty will be rendered. If not You Avatar will be shown.
{ pic === "" ? (
<View>
<Text>Screen if pic is empty</Text>
<View>
):
( <View>
<Avatar.Image
size= {150}
source={{ uri : 'data:image/png;base64,' + pic}}
/>
</View>
)

how to transform image from gallery or camera into base64?

I have a function that takes the image from the gallery or camera and sends it to an area where the user can view it.
import React, {useState} from 'react';
import {View, TouchableOpacity, Text, StyleSheet, Image} from 'react-native';
import ImagePicker from 'react-native-image-picker';
export default function Upload() {
const [avatar, setAvatar] = useState();
function imagePickerCallback(data) {
if (data.didCancel) {
return;
}
if (data.error) {
return;
}
if (data.customButton) {
return;
}
if (!data.assets[0].uri) {
return;
}
setAvatar(data.assets[0]);
}
return (
<View style={styles.container}>
<Image
source={{
uri: avatar
? avatar.uri
: 'https://mltmpgeox6sf.i.optimole.com/w:761/h:720/q:auto/https://redbanksmilesnj.com/wp-content/uploads/2015/11/man-avatar-placeholder.png',
}}
style={styles.avatar}
/>
<TouchableOpacity
style={styles.button}
onPress={() =>
ImagePicker.launchCamera(imagePickerCallback)
}>
<Text style={styles.buttonText}>camera</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() =>
ImagePicker.launchImageLibrary(imagePickerCallback)
}>
<Text style={styles.buttonText}>galery</Text>
</TouchableOpacity>
</View>
);
}
I'm filling the image source with the URI. I would like to know how to take this image and make it base64 to send it to firebase storage.
If I need to install a library, tell me which one to install.
If you read the library definition for options which is the first parameter. You can tell the library to return the base64 string. options: { includeBase64: true }
https://github.com/react-native-image-picker/react-native-image-picker#options
And that will return the below object with base64
https://github.com/react-native-image-picker/react-native-image-picker#asset-object
See below example:
import React, {useState} from 'react';
import {View, TouchableOpacity, Text, StyleSheet, Image} from 'react-native';
import ImagePicker from 'react-native-image-picker';
export default function Upload() {
const [avatar, setAvatar] = useState();
function imagePickerCallback(data) {
if (data.didCancel) {
return;
}
if (data.error) {
return;
}
if (data.customButton) {
return;
}
if (!data.assets[0].uri) {
return;
}
if((data.assets?.length ?? 0) > 0 && data.assets[0].base64){
//Here is my base64 string of assets[0]
}
setAvatar(data.assets[0]);
}
const options = {
includeBase64: true
}
return (
<View style={styles.container}>
<Image
source={{
uri: avatar
? avatar.uri
: 'https://mltmpgeox6sf.i.optimole.com/w:761/h:720/q:auto/https://redbanksmilesnj.com/wp-content/uploads/2015/11/man-avatar-placeholder.png',
}}
style={styles.avatar}
/>
<TouchableOpacity
style={styles.button}
onPress={() =>
ImagePicker.launchCamera(options, imagePickerCallback)
}>
<Text style={styles.buttonText}>camera</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() =>
ImagePicker.launchImageLibrary(options, imagePickerCallback)
}>
<Text style={styles.buttonText}>galery</Text>
</TouchableOpacity>
</View>
);
}

React Native - Is not a function - Is Undefined

I have the following code in React Native
import React from "react";
import {
StyleSheet,
Text,
View,
Button,
TextInput,
Image,
ScrollView
} from "react-native";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
apiData: [],
};
this.getButton();
}
deleteButton(Id){
fetch("http://192.168.2.22:9090/usuario/" + (Id), {
method: "DELETE"
})
.then(responseData => {
console.log(responseData.rows);
})
.done();
this.dataId = null;
}
render() {
const data = this.state.apiData;
let dataDisplay = data.map(function(jsonData) {
return (
<View style={styles.lista} key={jsonData.id}>
<View style={styles.bordeLista}>
<View style={styles.fila}>
<View style={styles.contenedorfoto}>
<Image
style={styles.foto}
source={require("./img/login.png")}
/>
</View>
<View style={styles.datos}>
<Text>Nombre: {jsonData.nombre}</Text>
<Text>E-mail: {jsonData.email}</Text>
<Text>Telefono: {jsonData.telefono}</Text>
</View>
</View>
<View style={styles.fila}>
<View style={styles.contenedorboton}>
<View style={styles.botoniz}>
<Button title="Modificar" onPress={() => {}} />
</View>
<View style={styles.botonde}>
<Button
title="Eliminar"
onPress={() => this.deleteButton(jsonData.Id)}
color="#ee4c4c"
/>
</View>
</View>
</View>
</View>
</View>
);
});
return (
<Text style={styles.titulo}>Usuarios desde BD MySQL</Text>
<ScrollView>
<View>{dataDisplay}</View>
</ScrollView>
</View>
);
}
}
And I want to call deleteButton() from this button
<Button
title="Eliminar"
onPress={() => this.deleteButton(jsonData.Id)}
color="#ee4c4c"
/>
But I get the following error, That the method is not a function and that it is not defined.
Error
How could I use the function? And I'm setting the parameter well (id). Thank you.
PS: I have deleted parts of the code and only left the most important, if you need the full code I can provide it
You're losing the reference to this because you're using an old-style lambda.
Replace this
data.map(function(jsonData) {
with an arrow function, like this
data.map(jsonData => {

Capture view-shot and save to device - React Native

I am developing an application where I have a button (TouchableHighlight) when pressing this button it is necessary to capture a screeshot of the current screen and save the file in the device.
My code does not show error, but when I press the button (TouchableHighlight) I get the message:
Image saved to file: ///data/user/0/com.appcamerav4/cache/ReactNative-snapshot-image8525057299267209213.jpg through Remote JS Debugging .
I can not open this directory and need to save the image to the device.
I'm new to react-native.
Follow my code below:
import React, { Component } from 'react';
import { Text, View, Image, StyleSheet, TouchableHighlight, WebView, StatusBar, Button } from 'react-native';
import { captureScreen } from "react-native-view-shot";
const zooMais = require('../imgs/zooMais.png');
const zooMenos = require('../imgs/zooMenos.png');
const imgScreeshot = require('../imgs/screeshot.png');
const btnZooMais = ()=>{
alert("Zoo Mais");
console.log("Zoom +");
}
const btnZooMenos = ()=>{
alert("Zoo Menos");
console.log("Zoom +");
}
const capitureScreen = ()=>{
captureScreen({
format: "jpg",
quality: 0.8,
}).then(
uri => console.log("Image saved to", uri),
error => console.error("Oops, snapshot failed", error)
);
}
export default class Monitor extends Component {
render() {
return (
<View style={ style.viewPrincipal }>
<StatusBar hidden />
<View style={ style.viewImagem } >
<WebView
style={style.video}
automaticallyAdjustContentInsets={true}
scalesPageToFit={true}
startInLoadingState={false}
contentInset={{top: 0, right: 0, left: 0, bottom: 0}}
scrollEnabled={true}
source={{uri: 'https://facebook.github.io/react/logo-og.png'}}
onNavigationStateChange = {this.handleNavigationStateChange}
/>
</View>
<View style={ style.viewRodape }>
<View style={style.viewMenu}>
<View >
<TouchableHighlight onPress={ btnZooMais } >
<Image style={style.imgMenu} source={zooMais } />
</TouchableHighlight>
</View>
<View>
<TouchableHighlight onPress={ capitureScreen }>
<Image style={style.imgMenu} source={ imgScreeshot } />
</TouchableHighlight >
</View>
<View>
<TouchableHighlight onPress={ btnZooMenos } >
<Image style={style.imgMenu} source={ zooMenos } />
</TouchableHighlight>
</View>
</View>
</View>
</View>
);
}
}
const style = StyleSheet.create({
viewPrincipal:{
flex: 1
},
viewImagem:{
flex:10,
justifyContent:'center',
alignItems:'stretch'
},
viewRodape:{
flex:1.3
},
viewMenu:{
flexDirection:'row',
justifyContent: 'space-between'
},
imgMenu:{
margin: 0,
marginBottom:0
},
video:{
flex:1
}
});
Make sure react-native-view-shot is correctly linked in XCode (might require a manual installation,
refer to React Native doc).
import React, { useRef } from "react"; // import useRef hook on top
const cardRef = useRef(); // Use this hook inside your func. component *important
// Define a function like this
const saveAsImage = async () => {
try {
const result = await captureRef(cardRef, {
result: "tmpfile",
quality: 1,
format: "png",
});
MediaLibrary.saveToLibraryAsync(result);
} catch (e) {
console.log(e);
}
};
Apply a prop eg. parentRef={cardRef} to your component, make sure the ref name matches which in this case is "cardRef".
Give any Button/TouchableOpacity
onPress={() => {saveAsImage();}}
To solve this problem you have to go on your App permission on your real mobile and allow for camera storage then you can easily save your ViewShot on Your Mobile.
go to App Permisssion in your App.info
allow Camera accesss storage
To save the screenshot to the camera roll, use this one: https://facebook.github.io/react-native/docs/cameraroll.html#savetocameraroll
More info: https://github.com/gre/react-native-view-shot Check the FAQ section

react-native router flux Actions is not navigating to other page

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
Image,
Button
} from 'react-native';
import Actions from 'react-native-router-flux';
import First from './First';
export default class Home extends Component{
componentWillMount() {
}
render(){
return(
<View>
<View style={{height:220,backgroundColor:'#DCDCDC'}}>
<Image style={{width:120,height:120,top:50,left:120,backgroundColor:'red'}}
source={require('./download.png')} />
</View>
<View style={{top:30}}>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<TouchableOpacity style= { styles.views}
onPress = {()=>{ Actions.First({customData: 'Hello!'}) }}>
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> Profile </Text>
</TouchableOpacity>
<TouchableOpacity style= { styles.views1} >
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> Health Tracker </Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
In the above code, Actions in not working means not navigating to First.js page, how can i edit my code, and i have not written anything in ComponentWillMount() function, what i should write inside that?ataomega
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity
} from 'react-native';
import Home from './Home';
export default class Prof extends Component{
constructor(){
super()
}
render(){
return (
<Navigator
initialRoute = {{ name: 'Home', title: 'Home' }}
renderScene = { this.renderScene }
navigationBar = {
<Navigator.NavigationBar
style = { styles.navigationBar }
routeMapper = { NavigationBarRouteMapper } />
}
/>
);
}
renderScene(route, navigator) {
if(route.name == 'Home') {
return (
<Home
navigator = {navigator}
{...route.passProps}
/>
)
}
}
}
var NavigationBarRouteMapper = {
LeftButton(route, navigator, index, navState) {
if(index > 0) {
return (
<View>
<TouchableOpacity
onPress = {() => { if (index > 0) { navigator.pop() } }}>
<Text style={ styles.leftButton }>
Back
</Text>
</TouchableOpacity>
</View>
)
}
else { return null }
},
RightButton(route, navigator, index, navState) {
if (route.openMenu) return (
<TouchableOpacity
onPress = { () => route.openMenu() }>
<Text style = { styles.rightButton }>
{ route.rightText || 'Menu' }
</Text>
</TouchableOpacity>
)
},
Title(route, navigator, index, navState) {
return (
<Text style = { styles.title }>
{route.title}
</Text>
)
}
};
First of all I recommend you to create a rounter component and make your app launch from there:
Something like this
import { Scene, Router, ActionConst } from 'react-native-router-flux';
import First from 'yourRoute';
const RouterComponent = () => {
<Router>
<Scene
key="First"
component={First}
initial />
... your other scenes
</Router>
}
export default RouterComponent;
then in your index page or wherever you load from just add this component
import React, { Component } from 'react'
import RouterComponent from './Router'
class AppContainer extends Component {
render() {
return (
<RouterComponent />
);
}
}
export default AppContainer;
now you can call it from your code. Any doubts ask them :P