I am new to react-native. I would like to open the camera on Pressable onPress event. Can anyone please give me the example of react-native-vision-camera. I have read the document. but really I don't know how to use the component. I have tried find-out the example, but no clue.
because I want to customize the video camera. for example, I want to show 1234 while recording. that's why I will go with react-native-vision-camera. I tried that package. but I couldn't able to open the camera. I am not sure what I am wrong and the documentation is also not clear for me. So I asked for help here. Can anyone please help ?
Upload.js
import React, {
useState,
useEffect,
useRef
} from 'react';
import { Provider as PaperProvider } from 'react-native-paper';
import { Avatar, Button, Card, Title, Chip, Paragraph } from 'react-native-paper';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
Image,
ImageBackground,
Pressable,
Dimensions,
PermissionsAndroid,
Platform,
TouchableOpacity
} from 'react-native';
import { Container } from 'native-base';
import Header from '../../Components/Header'
import colors from '../../Themes/Colors';
import Routes from '../../Navigation/Routes';
import useTranslation from '../../i18n';
import { IconX, ICON_TYPE } from '../../Icons';
import { ButtonX } from '../../Components';
import HeaderDoc from '../../Components/HeaderDoc';
import {
launchCamera,
launchImageLibrary
} from 'react-native-image-picker';
import { useStoreActions, useStoreState } from 'easy-peasy';
import { org_id } from '../../Config';
import { Camera, useCameraDevices } from 'react-native-vision-camera';
import ImagePicker from 'react-native-image-crop-picker';
import ApplicantDetails from './ApplicationDetails';
import { CameraComponent } from './CameraComponent';
const UploadDoc = ({ navigation, route }) => {
const { t } = useTranslation();
const isDarkMode = useColorScheme() === 'dark';
const tagList = ['a', 'b', 'c', 'D', 'E', 'F'];
const [fileData, setfileData] = useState('');
const [fileUri, setfileUri] = useState('');
const camera = useRef(null);
useEffect(() => {
(async () => {
const status = await Camera.requestCameraPermission();
setHasPermission(status === 'authorized');
})();
}, []);
return (
<SafeAreaView style={{ flex: 1, backgroundColor: colors.white }}>
<HeaderDoc title={'Upload Documents'} page={'1'} navigation={navigation} />
<View style={{ flex: 1, flexDirection: 'column' }}>
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{ marginBottom: 130, backgroundColor: colors.white }}>
<View style={{ marginHorizontal: 20, marginTop: 10, marginBottom: 50 }}>
<Pressable
style={{width: 100, height: 30, backgroundColor: colors.primary, justifyContent: 'center',alignSelf: 'center',alignItems: 'center'}}
onPress={()=> CameraComponent()}>
<Text style={{color: colors.white}}>Take Photo</Text>
</Pressable>
</View>
</ScrollView>
</View>
</SafeAreaView>
);
};
export default UploadDoc;
CameraComponent.js
import React, {
useState,
useEffect,
useRef
} from 'react';
import {
StyleSheet,
TouchableOpacity,
} from 'react-native';
import {Camera, useCameraDevices} from 'react-native-vision-camera';
export const CameraComponent = () => {
console.log("asmasas")
useEffect(() => {
(async () => {
const newCameraPermission = await Camera.requestCameraPermission()
const newMicrophonePermission = await Camera.requestMicrophonePermission()
})();
},[])
const devices = useCameraDevices()
const device = devices.back
if (device == null) return null;
return (
<Camera
style={StyleSheet.absoluteFill}
device={device}
isActive={true}
photo={true}
/>
)
}
First of all i assume youre using bare react native and not expo
Next then first you have to install the package via npm i or yarn install .
Then ill tell you for android
<uses-permission android:name="android.permission.CAMERA" />
<!-- optionally, if you want to record audio: -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
You have to add these in AndroidManifest.xml
Next get permission status by using
next then in your comp
App.js
export const App = () => {
useEffect(() => {
const newCameraPermission = await Camera.requestCameraPermission()
const newMicrophonePermission = await Camera.requestMicrophonePermission()
},[])
const devices = useCameraDevices()
const device = devices.back
if (device == null) return <LoadingView />
return (
<Camera
style={StyleSheet.absoluteFill}
device={device}
isActive={true}
/>
)
}
Hop it helps
Related
When I configure my links and url-scheme with react navigation it falls into the fallback error. Don't know why. Sometimes when making changes it worked but then it didn't. I have followed some tutorials that worked perfectly but when configuring it in my app It doesn't work. Please help. this is the code:
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
// NAVIGATION
import { LinkingOptions, NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import Ionic from 'react-native-vector-icons/Ionicons';
//APP SCREENS
import AppScreens from '../../Screens/App';
// CHECK OUT NAVIGATOR GROUPS
// AUTH SCREENS
import AuthScreens from '../../Screens/Auth';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { useSelector } from 'react-redux';
import store from '../../Store';
type RootState = ReturnType<typeof store.getState>;
export type RootStackParamList = {
Login: undefined;
SignUp: undefined;
Wizard: undefined;
};
const WizardStack = createNativeStackNavigator<RootStackParamList>();
const WizardStackScreen = () => {
return (
<WizardStack.Navigator>
<WizardStack.Screen
options={() => ({
headerShown: false,
})}
name="Wizard"
component={AuthScreens.Wizard}
/>
<WizardStack.Screen
options={() => ({
headerShown: true,
})}
name="Login"
component={AuthScreens.Login}
/>
<WizardStack.Screen
options={() => ({
headerShown: true,
})}
name="SignUp"
component={AuthScreens.SignUp}
/>
</WizardStack.Navigator>
);
};
const AppStack = createNativeStackNavigator();
const AppStackScreen = () => {
return (
<AppStack.Navigator>
<AppStack.Screen
options={() => ({
headerShown: false,
})}
name="App"
component={TabScreens}
/>
</AppStack.Navigator>
);
};
const App = () => {
const [isLoading, setIsLoading] = useState(false);
const [userLoaded, setUserLoaded] = useState(false);
const userLogged = useSelector((state: RootState) => state.auth.logged);
useEffect(() => {
if (userLogged) {
setUserLoaded(true);
}
}, [userLogged]);
const config = {
screens: {
Wizard: 'wizard',
Login: 'login',
SignUp: 'signup',
},
};
const linking: LinkingOptions<RootStackParamList> = {
prefixes: ['clientsapp://app'],
config,
};
return (
<SafeAreaProvider>
{isLoading ? (
<AuthScreens.Splash />
) : (
<NavigationContainer
// linking={linking}
fallback={
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>Loading... error</Text>
</View>
}>
<WizardStackScreen />
</NavigationContainer>
)}
</SafeAreaProvider>
);
};
export default App;
I have a problem with the react-native-signature-canvas library. When I test the signature in the app using the iOS and Android emulator in my Mac all is OK and the behavior is correct but when I publish the app on the Expo platform and I test the signature in the app using the physical device, the app restarts. Someone knows how can I resolve the problem?
I thought that the problem was the react-native-signature-canvas version but it's not the problem. I used the versions 3.6.0 and 4.0.0 without obtaining good results. Also, the version of Expo that I use is the 41.0.0.
Below I write my implementation of the signature with the react-native-signature-canvas library. Maybe I do something wrong. Thank you so much for your help.
import SignatureScreen from 'react-native-signature-canvas';
import React, {useRef, useState} from "react";
import {StyleSheet, Text, View} from 'react-native';
import Styles from "../styles/ModalPDF";
import {Divider, Modal, Portal} from "react-native-paper";
import Colors from "../constants/Colors";
import { scale } from '../services/Scaled';
import { attributeServiceHO } from "../services/AttributeServiceHO";
import {useSelector} from "react-redux";
const Signature = ({text, onOK, visible, onDismiss, setSign}) => {
const [firma ,setFirma] = useState(null);
const dataHistoriaOcupacional = useSelector(state => state.historiaOcupacional);
const caso = useSelector(state => state.medicos.caso);
const paciente = useSelector(state => state.paciente.paciente);
const medicoData = useSelector(state => state.medicos.medicos_obj);
const form = useSelector(state => state.medicos.siniestroSelected);
const rutMedico = useSelector(state => state.medicos.medicos_obj.rut);
const ref = useRef();
const handleSignature = signature => {
setSign(signature);
setFirma(signature)
if(typeof signature !== 'string'){
setSign(signature);
}else{
setSign(signature);
attributeServiceHO(dataHistoriaOcupacional, paciente, caso, medicoData, form, rutMedico)
.then((response) => {
let {codigo} = response;
if(codigo === 200){
onDismiss();
}
})
}
};
const handleEmpty = () => {
//console.log('Empty');
}
const handleClear = () => {
//console.log('clear success!');
}
const handleEnd = () => {
ref.current.readSignature();
}
const style = `.m-signature-pad--footer
.button.save {
background-color: ${Colors.primaryColorLight};
color: ${Colors.textButtonDark};
}
.m-signature-pad--footer
.button.clear {
background-color: ${Colors.white};
color: ${Colors.warningColorText};
}
`;
return (
<Portal>
<Modal visible={visible} onDismiss={onDismiss} contentContainerStyle={Styles.container}>
<View style={Styles.container}>
<View style={styles.preview}>
<Text style={Styles.title}>Firma aqui:</Text>
<Divider style={Styles.divider}/>
<SignatureScreen
onOK={(signature) => handleSignature(signature)}
onEmpty={handleEmpty}
descriptionText="Epeteista signature"
clearText="CLEAR"
confirmText="SIGN"
webStyle={style}
/>
</View>
</View>
</Modal>
</Portal>
);
}
const styles = StyleSheet.create({
preview: {
width: scale(360),
height: scale(415),
backgroundColor: "#F8F8F8",
justifyContent: "center",
alignItems: "center"
},
previewText: {
color: "#FFF",
fontSize: 14,
height: 40,
lineHeight: 40,
paddingLeft: 10,
paddingRight: 10,
backgroundColor: "#69B2FF",
width: 120,
textAlign: "center",
marginTop: 10
}
});
export default Signature;
I want to add a BottomNavigation to one of the screen of my App, I already used StackNavigation. How do I Implement the BottomNavigation into the routing flow?
I have tried doing it this way
import React from 'react';
import LoginForm from './src/Login/LoginForm';
import Register from './src/Register/Register';
import Timeline from './src/Timeline/Timeline';
import Post from './src/Product/Post';
import Profile from './src/Profile/Profile';
import IconWithBadge from './src/Utility/IconWithBadge';
import {createBottomTabNavigator,createStackNavigator,createSwitchNavigator, createAppContainer } from "react-navigation";
import { Font } from 'expo';
const AuthStack = createStackNavigator(
{
LoginScreen: {screen:LoginForm,navigationOptions: { header: null }},
RegisterScreen: {screen: Register,navigationOptions: { header: null }},
},
{
initialRouteName: "LoginScreen",
}
);
const AppStack = createStackNavigator(
createBottomTabNavigator(
{
TimelineScreen:Timeline,
ProductScreen:Post
},
{
defaultNavigationOptions: ({ navigation }) => ({
tabBarIcon: ({ focused, horizontal, tintColor }) => {
const { routeName } = navigation.state;
let IconComponent = Ionicons;
let iconName;
if (routeName === 'TimelineScreen') {
iconName = `ios-home${focused ? '' : '-outline'}`;
// Sometimes we want to add badges to some icons.
// You can check the implementation below.
IconComponent = IconWithBadge;
} else if (routeName === 'ProductScreen') {
iconName = `ios-plus`;
}
// You can return any component that you like here!
return <IconComponent name={iconName} size={25} color={tintColor} />;
},
}),
tabBarOptions: {
activeTintColor: 'tomato',
inactiveTintColor: 'gray',
},
}
)
)
const AppContainer = createAppContainer(
createSwitchNavigator(
{
Auth: AuthStack,
App: AppStack
}
));
export default class App extends React.Component {
render() {
return (
<AppContainer/>
);
}
}
Here is the IconWithBadge.js
import React, {Component} from 'react';
class IconWithBadge extends React.Component {
render() {
const { name, badgeCount, color, size } = this.props;
return (
<View style={{ width: 24, height: 24, margin: 5 }}>
<Ionicons name={name} size={size} color={color} />
{badgeCount > 0 && (
<View
style={{
// /If you're using react-native < 0.57 overflow outside of the parent
// will not work on Android, see https://git.io/fhLJ8
position: 'absolute',
right: -6,
top: -3,
backgroundColor: 'red',
borderRadius: 6,
width: 12,
height: 12,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={{ color: 'white', fontSize: 10, fontWeight: 'bold' }}>
{badgeCount}
</Text>
</View>
)}
</View>
);
}
}
Here is my App.js
import React from 'react';
import LoginForm from './src/Login/LoginForm';
import Register from './src/Register/Register';
import Timeline from './src/Timeline/Timeline';
import Post from './src/Product/Post';
import Profile from './src/Profile/Profile';
import IconWithBadge from './src/Utility/IconWithBadge';
import {createBottomTabNavigator,createStackNavigator,createSwitchNavigator, createAppContainer } from "react-navigation";
const AuthStack = createStackNavigator(
{
LoginScreen: {screen:LoginForm,navigationOptions: { header: null }},
RegisterScreen: {screen: Register,navigationOptions: { header: null }},
},
{
initialRouteName: "LoginScreen",
}
);
const AppStack = createStackNavigator(
{
TimelineScreen: {screen:Timeline,navigationOptions: { header: null,title: "Welcome to the dashboard" }}
}
)
const AppContainer = createAppContainer(
createSwitchNavigator(
{
Auth: AuthStack,
App: AppStack
}
));
export default class App extends React.Component {
render() {
return (
<AppContainer/>
);
}
}
My code seems not to work with my set up here, how do I place the Bottom Navigation routing into the stacknavgiation in order to see it on the TimelineScreen
Modify your code as following. Essentially replace createSwitchNavigator with createBottomTabNavigator
const AppContainer = createAppContainer(
createBottomTabNavigator(
{
Auth: AuthStack,
App: AppStack
}
));
I'm totally new to expo and react native
I'm trying to use ImageBackground
I use it as the code below but I get this error "Unable to resolve "./assets/back.jpg" from "app\components\Login.js" "
My image is already in assets folder in my project
And also when I try to import font I get the same error
Does it need to import something before using or something else?
I also Tried it by not importing the image and adding the path directly to source property
Login.js
import React, { Component } from 'react';
import back from './assets/back.jpg';
import {
StyleSheet,
Text,
View,
TextInput,
KeyboardAvoidingView,
TouchableOpacity,
AsyncStorage,
Image,
ImageBackground,
} from 'react-native';
import {createStackNavigator, createAppContainer} from 'react-navigation';
export default class Login extends React.Component {
static navigationOptions = {
header: null,
};
constructor(props) {
super(props);
this.state = {
username:'',
password:'',
}
}
componentDidMount(){
this._loadInitialState().done();
}
_loadInitialState = async () =>{
var value = await AsyncStorage.getItem('user');
if (value !=null){
this.prop.navigation.navigate('Profile');
}
}
render() {
return (
<ImageBackground source={back} style={styles.backImg}>
<KeyboardAvoidingView behavior='padding' style={styles.wrapper}>
<View style={styles.container}>
<Image
style={styles.logo}
source={require('/MyFirst/assets/logo.png')}
/>
<TextInput
style={styles.textInput} placeholder='Username'
onChangeText={(username) =>this.setState({username}) }
underlineColorAndroid = 'transparent'
/>
<TextInput
style={styles.textInput} placeholder='Password'
onChangeText={(password) =>this.setState({password}) }
underlineColorAndroid = 'transparent'
/>
<TouchableOpacity style={styles.btn}
onPress={this.login}>
<Text style={styles.btnText}>Login</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
wrapper:{
flex:1,
},
container:{
flex:1,
alignItems:'center',
justifyContent:'center',
backgroundColor:'#e5ffd3',
paddingLeft:40,
paddingRight:40,
},
logo:{
width: 250,
height: 250,
},
textInput:{
alignSelf:'stretch',
padding:16,
marginBottom:20,
backgroundColor:'#fff',
borderWidth: 1,
borderColor: '#d6d7da',
borderRadius: 25,
},
btn:{
alignSelf:'stretch',
backgroundColor:'#589e25',
padding:20,
alignItems: 'center',
borderRadius: 25,
},
btnText:{
color: '#ffffff',
},
})
App.js
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
import {createStackNavigator, createAppContainer} from 'react-navigation';
import Login from './app/components/Login'
import Profile from './app/components/Profile'
const MainNavigator = createStackNavigator({
Home: {screen: Login},
Profile: {screen: Profile},
});
const App = createAppContainer(MainNavigator);
export default App;
You should use ImageBackground in this way. It will solve your problem
<ImageBackground source={require('../../assets/back.jpg')} style={styles.backImg}>
Working example can be found here Link
This should be included in the react-native APIs but I cannot seem to find any API included out of the box.
I want to open up the camera on the click of a button. I can see some APIs just for iOS but react-native should make things cross-platform.
Does anyone know how to access the camera (not the gallery) using react-native?
You might like to use react-native-camera module for this.
Here's an example usage of the library:
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
import Camera from 'react-native-camera';
class BadInstagramCloneApp extends Component {
render() {
return (
<View style={styles.container}>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
</Camera>
</View>
);
}
takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
.then((data) => console.log(data))
.catch(err => console.error(err));
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});
AppRegistry.registerComponent('BadInstagramCloneApp', () => BadInstagramCloneApp);
Currently react-native-camera is deprecated and if you want to achieve native performance and reach feature support good choice is https://github.com/mrousavy/react-native-vision-camera
Features:
Photo, Video and Snapshot capture
Customizable devices and multi-cameras (smoothly zoom out to "fish-eye" camera)
Customizable FPS
Frame Processors (JS worklets to run QR-Code scanning, facial recognition, AI object detection, realtime video chats, ...)
Smooth zooming (Reanimated)
Fast pause and resume
HDR & Night modes
Example:
function App() {
const devices = useCameraDevices('wide-angle-camera')
const device = devices.back
if (device == null) return <LoadingView />
return (
<Camera
style={StyleSheet.absoluteFill}
device={device}
isActive={true}
/>
)
}
Documentation:
https://mrousavy.com/react-native-vision-camera/docs/guides
In React Native you can access the camera by first installing it using NPM:
npm install react-native-camera --save
react-native link react-native-camera
Then use this in your Component:
takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
.then((data) => console.log(data))
.catch(err => console.error(err));
}
See this github repo for full example:
https://github.com/lwansbrough/react-native-camera
I found react-native-picker image picker handier for my needs, it can be useable for both camera and gallery. for the bellow example you need to install version: "react-native-image-picker": "^3.3.2",
https://www.npmjs.com/package/react-native-image-picker
import React, {useState, useEffect} from 'react';
import {StyleSheet, Text, View, Image} from 'react-native';
import cameraImage from '../../../../assets/icons/camera.png';
import galleryImage from '../../../../assets/icons//gallery.png';
import {TouchableWithoutFeedback} from 'react-native-gesture-handler';
import * as ImagePicker from 'react-native-image-picker';
import {PermissionsAndroid} from 'react-native';
const ImagePicker = () => {
const [responseCamera, setResponseCamera] = React.useState(null);
const [responseGallery, setResponseGallery] = React.useState(null);
const openCameraWithPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: 'App Camera Permission',
message: 'App needs access to your camera ',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
ImagePicker.launchCamera(
{
mediaType: 'photo',
includeBase64: false,
maxHeight: 200,
maxWidth: 200,
},
(response) => {
console.log(response);
setResponseCamera(response);
setResponseGallery(null);
},
);
} else {
console.log('Camera permission denied');
}
} catch (err) {
console.warn(err);
}
};
return (
<View
style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around',
margin: 4,
}}>
<TouchableOpacity onPress={() => openCameraWithPermission()}>
{responseCamera === null ? (
<Image style={styles.icon} source={cameraImage} />
) : (
<Image style={styles.icon} source={{uri: responseCamera.uri}} />
)}
</TouchableOpacity>
<TouchableOpacity
onPress={() =>
ImagePicker.launchImageLibrary(
{
mediaType: 'photo',
includeBase64: false,
maxHeight: 200,
maxWidth: 200,
},
(response) => {
setResponseGallery(response);
setResponseCamera(null);
},
)
}>
{responseGallery === null ? (
<Image style={styles.icon} source={galleryImage} />
) : (
<Image style={styles.icon} source={{uri: responseGallery.uri}} />
)}
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
icon: {
height: 50,
width: 50,
},
});
export default ImagePicker;
permissions for android:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />