react-native-vision-camera doesn't appears after initialization
I was expecting Camera or something like this but screen stucks on Loading
I've tried a lot of things but couldn't solve the problem. Documentation didn't give any of useful information
import { Alert, StyleSheet, View } from "react-native";
import { Camera, useCameraDevices } from "react-native-vision-camera";
import { Loading } from "../components/Loading/Loading";
export const CameraScreen: FC = () => {
const devices = useCameraDevices();
const device = devices.back;
if (device == null) return <Loading />;
return (
<View style={style.screen}>
<Camera
device={device}
isActive={true}
style={StyleSheet.absoluteFill}
/>
</View>
);
};
const style = StyleSheet.create({
screen: {
flex: 1,
backgroundColor: "#222",
},
camera: {
flex: 1,
alignItems: "center",
justifyContent: "flex-end",
},
});```
Put cameraRef on component.
const cameraRef = React.useRef(null);
<Camera
ref={cameraRef} /* use cameraRef.current.takePhoto(): Promise<dataPhoto> */
photo={true} /* or video={true} */
device={device}
isActive={true}
style={StyleSheet.absoluteFill}
/>
See oficial docs.
Related
Peace...
I'm trying to make a text input component which receives input from user like below:
All inputs from user...
//AppTextInput (main supplier)
import React, { useState } from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
import { MaterialCommunityIcons } from '#expo/vector-icons';
import defaultStyles from '../config/styles';
export default function AppTextInput({ icon, ...otherProps }) {
// const [firstName, setFirstName] = useState('');
// const [isNew, setIsNew] = useState(false);
return (
<View style={styles.container}>
{icon && <MaterialCommunityIcons name={icon} size={20}
color={defaultStyles.colors.medium} style={styles.icon}
/>}
<TextInput style={defaultStyles.text} {...otherProps}
placeholderTextColor={defaultStyles.colors.medium}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
backgroundColor: defaultStyles.colors.light,
borderRadius: 25,
flexDirection: 'row',
width: '100%',
padding: 15,
marginVertical: 10,
},
icon: {
marginRight: 10,
alignSelf: 'center',
}
});
//config/styles (styling code)
import { Platform } from 'react-native';
import colors from './colors';
export default {
colors,
text: {
color: colors.dark,
fontSize: 18,
fontFamily: Platform.OS === "android" ? "Roboto" : "Avenir",
},
}
//AppFormField (for forms)
import React from 'react';
import { StyleSheet } from 'react-native';
import { useFormikContext } from 'formik';
import AppTextInput from '../AppTextInput';
import ErrorMessage from './ErrorMessage';
export default function AppFormField({ name, ...otherProps }) {
const { errors, handleChange, setFieldTouched, touched } = useFormikContext();
return (
<>
<AppTextInput
onBlur={() => setFieldTouched(name)}
onChangeText={handleChange(name)}
{...otherProps}
/>
<ErrorMessage error={errors[name]} visible={touched[name]} />
</>
);
}
//ListingEditScreen (this the main window to user)
export default function ListingEditScreen() {
return (
<Screen style={styles.container}>
<Form
initialValues={{
title: "",
price: "",
description: "",
category: null,
}}
onSubmit={(values) => console.log(values)}
validationSchema={validationSchema}
>
<AppFormField maxLength={255} name="title" placeholder="Title" />
<AppFormField
keyboardType="numeric"
maxLength={8}
name="price"
placeholder="Price"
width={120}
/>
<Picker
items={categories}
name="category"
numberOfColumns={3}
PickerItemComponent={CategoryPickerItem}
placeholder="Category"
width="50%"
/>
<AppFormField
maxLength={255}
multiline
name="description"
numberOfLines={3}
placeholder="Description"
/>
<SubmitButton title="Post" />
</Form>
</Screen>
);
}
const styles = StyleSheet.create({
container: {
padding: 10,
},
});
but my problem is that the input field only gets acitvated when I touch the placeholder text and not any other part of the text input field!
My main problem
So how can I solve this problem so that I can touch any part of the input field and it gets activated!
Thank-you!
I just started learning and practicing React Native and I have run into the first problem that I cant seem to solve by myself.
I have the following code, which is very simple, but the Alert.alert() does not work when I run it on the web. if I click the button nothing happens, however, when i click the button on an iOS or android simulator it works fine.
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, Button, View, Alert } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.headerStyle} >Practice App</Text>
<Text style={{padding: 10}}>Open up App.js to start working on your app!</Text>
<Button
onPress={() => alert('Hello, Nice To Meet You :)')}
title="Greet Me"
/>
<StatusBar style="auto" />
</View>
);
}
I also know that alert() works on all three devices, however, I want to understand why Alert.alert() only works for iOS and Android.
My question is more so for understanding rather than finding a solution. Is the only solution to use alert(), or am I implementing Alert.alert() in the wrong way?
This workaround basically imitates react-native's Alert behavior with browsers' window.confirm method:
# alert.js
import { Alert, Platform } from 'react-native'
const alertPolyfill = (title, description, options, extra) => {
const result = window.confirm([title, description].filter(Boolean).join('\n'))
if (result) {
const confirmOption = options.find(({ style }) => style !== 'cancel')
confirmOption && confirmOption.onPress()
} else {
const cancelOption = options.find(({ style }) => style === 'cancel')
cancelOption && cancelOption.onPress()
}
}
const alert = Platform.OS === 'web' ? alertPolyfill : Alert.alert
export default alert
Usage:
Before:
import { Alert } from 'react-native'
Alert.alert(...)
After:
import alert from './alert'
alert(...)
Source & Credits: https://github.com/necolas/react-native-web/issues/1026#issuecomment-679102691
React Native is an open-source mobile application framework for Android, iOS and Web but there is not an Alert Component for Web but I have found a package which will provide you solutation. That is it to install package
npm i react-native-awesome-alerts
This example will help you
import React from "react";
import { StyleSheet, Text, View, TouchableOpacity } from "react-native";
import Alert from "react-native-awesome-alerts";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { showAlert: false };
}
showAlert = () => {
this.setState({
showAlert: true,
});
};
hideAlert = () => {
this.setState({
showAlert: false,
});
};
render() {
const { showAlert } = this.state;
return (
<View style={styles.container}>
<Text>Practice App</Text>
<Text style={{ padding: 10 }}>
Open up App.js to start working on your app!
</Text>
<TouchableOpacity
onPress={() => {
this.showAlert();
}}
>
<View style={styles.button}>
<Text style={styles.text}>Greet Me</Text>
</View>
</TouchableOpacity>
<Alert
show={showAlert}
message="Hello, Nice To Meet You :"
closeOnTouchOutside={true}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
backgroundColor: "#fff",
},
button: {
margin: 10,
paddingHorizontal: 10,
paddingVertical: 7,
borderRadius: 5,
backgroundColor: "#AEDEF4",
},
text: {
color: "#fff",
fontSize: 15,
},
});
I have installed react-native-pdf and rn-fetch-blob packages to show pdf file.It work's fine on simulator but for some reason i am getting "Error: open failed: ENOENT (No such file or directory)".
Here is my code below:
import React, { Component } from 'react';
import {
StyleSheet,
Dimensions,
View
} from 'react-native';
import Pdf from 'react-native-pdf';
// Screen that shows the contents of a PDF
export default class OpenPdf extends Component {
static navigationOptions = {
title: 'Product Variants'
};
render() {
const source = require('../assets/Product_Variants_Electric_Connections.pdf');
return (
<View style={{width: '100%', height: '100%'}}>
<Pdf style={styles.pdf}
source={source}
onLoadComplete={(numberOfPages, filePath) => {
alert(`number of pages: ${numberOfPages}`);
}}
onPageChanged={(page, numberOfPages) => {
alert(`current page: ${page}`);
}}
onError={(error) => {
alert(`error`+error);
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
pdf: {
flex: 1,
width: Dimensions.get('window').width
}
});
I have already went through many links, none of the issue is similar to mine.
Kindly please suggest what am I missing.
As suggested by #Hardik Virani above in comment, I have removed local url and did like below:
render() {
const source = {uri:'bundle-assets://Product_Variants_Electric_Connections.pdf', cache: true};
return (
<View style={{width: '100%', height: '100%'}}>
<Pdf style={styles.pdf}
source={source}
/>
</View>
);
And Remember Just put your actual pdf in the android/app/src/main/assets/pdf folder of your project.
Does anyone know how to resolve this error?
"Error while updating property 'src' of a view managed by:
RCTImageView"
This error appear when the component is rendering. I think that the images do not give them time to download or something like this.
Dependences:
"firebase": "^4.8.2",
"react": "16.0.0-alpha.12",
"react-native": "0.47",
"react-native-image-picker": "^0.26.7",
ERROR
Gallery.js
import React, { Component } from 'react';
import { View, Image, ScrollView, StyleSheet, Dimensions } from 'react-native';
import { connect } from 'react-redux';
import firebase from '../../config/firebase';
import { nameChanged } from '../../actions';
import { CardSectionTransp, InputBlack } from '../common';
import { SnapshotToArray } from '../../config/helpers';
const { width, height } = Dimensions.get('window');
class EventDetail extends Component {
constructor(props) {
super(props);
this.state = {
images: [],
objImages: []
};
}
componentWillMount() {
firebase.database().ref().child('images').orderByChild('order').once('value', snapshot => {
const images = SnapshotToArray(snapshot);
this.setState({ objImages: images });
const arrayImages = [];
for (const image of images) {
const starsRef = firebase.storage().refFromURL('gs://bealegendapp.appspot.com/images/' + image.path);
// Get the download URL
starsRef.getDownloadURL().then((url) => {
arrayImages.push(url);
this.setState({ objImages: arrayImages });
}).catch((error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/object_not_found':
// File doesn't exist
break;
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect the server response
break;
default:
break;
}
});
}
});
}
onNameChange(text) {
this.props.nameChanged(text);
}
render() {
return (
<ScrollView style={styles.container}>
<CardSectionTransp>
<InputBlack
label="Nombre"
onChangeText={this.onNameChange.bind(this)}
value={this.props.name}
/>
</CardSectionTransp>
<View style={{ flex: 1, flexDirection: 'row', flexWrap: 'wrap', marginTop: 10 }}>
{this.state.objImages && this.state.objImages.length > 0 &&
this.state.objImages.map((image, key) => {
return (
<View key={key} style={{ width: width / 3 }}>
<Image <-------------EEEEEEERRRRRRRROOOOOOORRRRRRR!!!!
source={{ uri: image }}
style={styles.image}
/>
</View>
);
})
}
{this.props.photos &&
this.props.photos.map((image, key) => {
return (
<View key={key} style={{ width: width / 3 }}>
<Image
source={{ uri: image }}
style={styles.image}
/>
</View>
);
})
}
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
paddingBottom: 123
},
image: {
height: height / 5,
resizeMode: 'contain',
width: width / 3,
borderWidth: 1,
borderColor: 'white'
}
});
const mapStateToProps = ({ gallery }) => {
const { name, photos } = gallery;
return { name, photos };
};
export default connect(mapStateToProps, {
nameChanged
})(EventDetail);
Resolved.
I was trying to get storage uri in Component. Is better get it when upload an image and save it in DataBase.
Then... I only to request Images and put storage uri saved in DataBase in source={{ uri: }}.
For anyone else that happens across this issue - i also had it and temporarily got around it with:
{ this.state.myImage !== '' ?
<View>
<Image source={this.state.myImage} />
<Button title="keep img?" onPress={this.setImage} />
</View> : null
}
I want to implement a flip effect in my React Native app, similar like described here:
https://www.codementor.io/reactjs/tutorial/building-a-flipper-using-react-js-and-less-css
My question is. Can I achieve it somehow with the help of some library like 'Animations' https://facebook.github.io/react-native/docs/animations.html or I have to play with 'plain' CSS styles.
What is the 'good practive' for such animations in React Native?
class CardBack extends Component {
render() {
return (
<TouchableOpacity onPress={this.flip}>
<View style={styles.scrumCardBorder}>
<View style={styles.cardBack}>
</View>
</View>
</TouchableOpacity>
);
}
flip() {
this.setState({flipped: !this.state.flipped})
}
}
class CardFront extends Component {
render() {
return (
<TouchableOpacity>
<View style={styles.scrumCardBorder}>
<View style={styles.cardFront}>
<Text style={styles.cardValue}>5</Text>
</View>
</View>
</TouchableOpacity>
);
}
}
We can use transform and Interpolate to make 3D rotate Animation.
class RotateAnimation extends React.Component {
_rotateValue = new Animated.Value(0);
startAnimated = () => {
Animated.timing(this._rotateValue, {
toValue: 360,
duration: 800,
useNativeDriver: true
}).start()
}
getTransform = () => {
const rotate = this._rotateValue.interpolate({
inputRange: [0, 180, 360],
outputRange: ['0deg', '180deg', '360deg'],
extrapolate: 'clamp',
})
if (this.props.horizontal) {
return {
transform: {
perspective: WINDOW_WIDTH,
rotateX: rotate
}
}
}
return {
transform: {
perspective: WINDOW_WIDTH,
rotateY: rotate
}
}
}
render() {
return (<Animated.View style={[style, ]} />
{this.props.children}
</Animated.View>)
}
}
If you want to use transform around a certain point. Can try this.
Use Animated api for these transformations.
Note: Rotation along the axis(ie, rotateX or rotateY) with perspective will give you the feel of flipping.
Always use useNativeDriver: true for better performance.
Example code:
import React, {Component} from 'react';
import {View, Animated, StyleSheet, Button} from 'react-native';
export default class Container extends Component {
constructor() {
super();
this.animation = new Animated.ValueXY({x: 0, y: 0});
const inputRange = [0, 1];
const outputRange = ['0deg', '180deg'];
this.rotateX = this.animation.x.interpolate({inputRange, outputRange});
this.rotateY = this.animation.y.interpolate({inputRange, outputRange});
}
flip = (val) => {
this.animation[val].setValue(0);
Animated.timing(this.animation[val], {
toValue: 1,
duration: 500,
useNativeDriver: true,
}).start();
};
render() {
const {rotateX, rotateY} = this;
return (
<View style={styles.container}>
<Animated.View
style={{
...styles.item,
transform: [{rotateX}, {rotateY}, {perspective: 500}],
}}
/>
<Button title="flip x " onPress={() => this.flip('x')} />
<Button title="flip y " onPress={() => this.flip('y')} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {flex: 1, alignItems: 'center', justifyContent: 'center'},
item: {
height: 200,
width: 200,
backgroundColor: 'red',
marginBottom: 20,
},
});