react native camera undefined - camera

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() {
this.camera.capture()
.then((data) => console.log(data))
.catch(err => console.error(err));
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
height: Dimensions.get('window').height,
width: Dimensions.get('window').width
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});
AppRegistry.registerComponent('AwesomeProject', () => BadInstagramCloneApp);
I used the following steps to resolve the issue :
Delete the node_modules folder - rm -rf node_modules && npm install
Reset packager cache - rm -fr $TMPDIR/react-* or node_modules/react-native/packager/packager.sh --reset-cache
Clear watchman watches - watchman watch-del-all
Recreate the project from scratch
But i still get an error.

Make sure you have made the settings right, including running $ react-native link react-native-camera and others according the documentation.

You can try to use
var Camera = require('react-native-camera')

Replace the line:
import Camera from 'react-native-camera';
With this line:
import {RNCamera} from 'react-native-camera';
Change <Camera></Camera> tag to <RNCamera></RNCamera>.
Remove the aspect attribute from RNCamera tag.

Related

Unable to Apply Layout Animation Using Reanimated API

I'm trying to apply layout animation to a FlatList upon adding and deleting a goal (list item) using the Reanimated API. I'm mainly following this tutorial from the Reanimated docs but I don't know why the animation is not applied when list items are added or removed. I should also inform that I'm only testing this on an Android device. Here is the code:
App.js (contains FlatList)
import { useState } from "react";
import { Button, FlatList, StyleSheet, View } from "react-native";
import GoalInput from "./components/GoalInput";
import GoalItem from "./components/GoalItem";
export default function App() {
const [goalList, setGoalList] = useState([]);
const [isModalOpen, setIsModalOpen] = useState(false);
const styles = StyleSheet.create({
appContainer: {
paddingTop: 50,
},
});
function startAddGoalHandler() {
setIsModalOpen(true);
}
// spread existing goals and add new goal
function addGoalHandler(enteredGoalText) {
setGoalList((currentGoals) => [
...currentGoals,
{ text: enteredGoalText, id: Math.random().toString() },
]);
}
function deleteGoalHandler(id) {
setGoalList((currentGoals) =>
currentGoals.filter((existingGoals) => existingGoals.id !== id)
);
}
return (
<View style={styles.appContainer}>
<Button
title='Add New Goal'
color='indigo'
onPress={startAddGoalHandler}
/>
{isModalOpen && (
<GoalInput
isModalOpen={isModalOpen}
setIsModalOpen={setIsModalOpen}
onAddGoal={addGoalHandler}
></GoalInput>
)}
<FlatList
keyExtractor={(item, index) => {
return item.id;
}}
data={goalList}
renderItem={(itemData) => {
return (
<GoalItem
onGoalDelete={deleteGoalHandler}
itemData={itemData}
/>
);
}}
/>
</View>
);
}
GoalItem.js (list item)
import React from "react";
import { Pressable, StyleSheet, Text } from "react-native";
import Animated, { Layout, LightSpeedInLeft, LightSpeedOutRight } from "react-native-reanimated";
const GoalItem = ({ itemData, onGoalDelete }) => {
const styles = StyleSheet.create({
goalCards: {
elevation: 20,
backgroundColor: "white",
shadowColor: "black",
height: 60,
marginHorizontal: 20,
marginVertical: 10,
borderRadius: 10,
},
});
return (
<Animated.View
style={styles.goalCards}
entering={LightSpeedInLeft}
exiting={LightSpeedOutRight}
layout={Layout.springify()}
>
<Pressable
style={{ padding: 20 }}
android_ripple={{ color: "#dddddd" }}
onPress={() => onGoalDelete(itemData.item.id)}
>
<Text style={{ textAlign: "center" }}>
{itemData.item.text}
</Text>
</Pressable>
</Animated.View>
);
};
export default GoalItem;
I've even tried replacing the FlatList with View but to no avail. I suspect that Reanimated isn't properly configured for my project, if I wrap some components with <Animated.View>...</Animated.View> (Animated from Reanimated and not the core react-native module) for example the child components will not show. Reanimated is installed through npm
Any help is appreciated, thanks!

Why is React Native FlatList not working on Android but it is for Web?

I am using Expo to build a react native app with AWS for the backend.
I am trying to display a list of friends using FlatList and the AWS data. The list works and is visible on my web browser, but for some reason, it is not displaying on my Android phone. What might the issue be?
FriendsList.tsx
import { API, graphqlOperation } from 'aws-amplify';
import * as React from 'react';
import {useEffect, useState} from 'react';
import { FlatList, View, ScrollView, Text, StyleSheet } from 'react-native';
import { listUsers } from '../graphql/queries';
import FriendsListItem from '../components/FriendsListItem';
export default function FriendsList() {
const [ users, setUsers ] = useState([]);
useEffect( () => {
const fetchUsers = async () => {
try {
const usersData = await API.graphql(
graphqlOperation(
listUsers
)
)
setUsers(usersData.data.listUsers.items);
} catch (e) {
}
}
fetchUsers();
},[])
return (
<View style={ styles.container }>
<FlatList
style={{ width: '100%' }}
data={users}
renderItem={({ item }) => <FriendsListItem user={item} />}
keyExtractor={(item) => item.id}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
FriendsListItem.tsx
import * as React from 'react';
import { View, Text, StyleSheet, Image, TouchableWithoutFeedback } from 'react-native';
import { API, graphqlOperation, Auth } from "aws-amplify";
import { User } from './types';
export type FriendsListItemProps = {
user: User;
}
const FriendsListItem = ( props: FriendsListItemProps ) => {
const { user } = props;
return (
<TouchableWithoutFeedback>
<View style={styles.container}>
<View style={styles.lefContainer}>
<Image source={{ uri: user.imageUri }} style={styles.avatar}/>
<View style={styles.midContainer}>
<Text style={styles.username}>{user.name}</Text>
<Text numberOfLines={2} style={styles.status}>{user.email}</Text>
</View>
</View>
</View>
</TouchableWithoutFeedback>
);
}
export default FriendsListItem;
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
width: "100%",
justifyContent: 'space-between',
//height: '100%',
},
lefContainer: {
flexDirection: 'row',
padding: 16,
},
midContainer: {
justifyContent: 'space-around'
},
avatar: {
width: 60,
height: 60,
borderRadius: 50,
marginRight: 15,
},
username: {
fontWeight: 'bold',
fontSize: 16,
},
status: {
fontSize: 16,
color: 'grey',
},
});
Looking at the code example, in your FriendsListItem component, any time you use your "user" prop, you need to change it. For example, change this:
user.imageUri
to this:
user.item.imageUri
What you are passing in is an object (e.g. user), which then contains another object (e.g. item), which finally contains your data (e.g. imageUri).
I figured it out. Turns out I am just an idiot. The expo app on my phone was logged into a different account so that's why it wasn't showing any friends for that user.

<SafeAreaView> not work (Views go above the notification tab)

For some reason safeAreaView does not work in my code, Views go above the notification tab. I've tried a few things but couldn't. I tried to take the style of safeAreaView and create a view below safeAreaView that involves all the code and then in that view put that style, but it didn't work either!
import React from 'react';
import { SafeAreaView, StyleSheet, View, Image, Text } from 'react-native';
export default function Menu({ navigation }){
return <SafeAreaView style={styles.container}>
<View style={styles.profile}>
<Image source={{uri: 'https://elysator.com/wp-content/uploads/blank-profile-picture-973460_1280-e1523978675847.png'}} style={styles.imageProfile} />
<Text style={styles.name}>StackOverFlow</Text>
</View>
</SafeAreaView>
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
profile: {
flexDirection: 'row',
backgroundColor: '#EEE',
},
imageProfile: {
width: 34,
marginBottom: 5,
marginTop: 5,
borderRadius: 44/2,
marginLeft: 10,
height: 34
},
name: {
alignSelf: 'center',
marginLeft: 10,
fontSize: 16
}
});
According to react-native docs:
The purpose of SafeAreaView is to render content within the safe area
boundaries of a device. It is currently only applicable to iOS devices
with iOS version 11 or later.
I would advise you to not just follow safeAreaView functionalities. rather its better extract the Status bar height and give a marginTop to whole container so its always below the status bar. See the code below and also the working expo snack solution:
import React from 'react';
import { SafeAreaView, StyleSheet, View, Image, Text,StatusBar } from 'react-native';
export default function Menu({ navigation }){
return <SafeAreaView style={styles.container}>
<View style={styles.profile}>
<Image source={{uri: 'https://elysator.com/wp-content/uploads/blank-profile-picture-973460_1280-e1523978675847.png'}} style={styles.imageProfile} />
<Text style={styles.name}>StackOverFlow</Text>
</View>
</SafeAreaView>
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop:StatusBar.currentHeight
},
profile: {
flexDirection: 'row',
backgroundColor: '#EEE',
},
imageProfile: {
width: 34,
marginBottom: 5,
marginTop: 5,
borderRadius: 44/2,
marginLeft: 10,
height: 34
},
name: {
alignSelf: 'center',
marginLeft: 10,
fontSize: 16
}
});
Expo link :expo-snack
Hope it helps. feel free for doubts
The SafeAreaView from 'react-native-safe-area-context' just worked for me.
The react-native version doesn't work on Android or early iOS versions.
Specifically you want to use:
import { SafeAreaView } from 'react-native-safe-area-context'
and not
import { SafeAreaView } from 'react-native'
If you're not already using react-native-safe-area-context then you might want to read the documentation as it also requires that you use the SafeAreaProvider component at a higher level in your app.
Try "resizeMode" in imageview
enum('cover', 'contain', 'stretch', 'repeat', 'center')
https://facebook.github.io/react-native/docs/image#resizemode
None of these work for me ,
so i try this and it solve the problem.
First: Import SafeAreaProvider from react-native-safe-area-context as shown below.
import { SafeAreaProvider} from 'react-native-safe-area-context';
Second : give marginTop to it, in my case is was 13%, adjust according to your needs, as shown below .
<SafeAreaProvider style={{marginTop:"13%"}} >
<Home/>
...
<SafeAreaProvider/>
Let me know if this was helpful.

React-Native : How to rotate base 64 image

I have PNG image in base64 format which will be saved in server, But before saving into server image need to be rotated.
I have gone through this link, but it doesn't seem possible in react-native.
Is there any way in react-native to rotate base64 image?
I tried using gm package, But i end up with lot of errors in node_modules. Has any one else tried this package?
There is a package react-native-image-rotate
you can rotate any image including base64
Installation
First install the package via npm
$ npm install react-native-image-rotate
then use rnpm to link native libraries
$ react-native link react-native-image-rotate
usage
static rotateImage(
uri: string,
angle: number,
success: (uri: string) => void,
failure: (error: Object) => void
) : void
Example
import React from 'react';
import { StyleSheet, View,Image, TouchableHighlight,Text } from 'react-native';
import ImageRotate from 'react-native-image-rotate';
const string = 'Your base64 image here'
export default class App extends React.Component{
constructor(props){
super(props);
this.state = {
image: string,
currentAngle: 0,
width: 150,
height: 240,
};
this.rotate = this.rotate.bind(this);
}
rotate = (angle) => {
const nextAngle = this.state.currentAngle + angle;
ImageRotate.rotateImage(
string,
nextAngle,
(uri) => {
console.log(uri, 'uri')
this.setState({
image: uri,
currentAngle: nextAngle,
width: this.state.height,
height: this.state.width,
});
},
(error) => {
console.error(error);
}
);
}
render(){
return (
<View style={{flex:1,alignItems:'center'}}>
<Image source={{uri: this.state.image}} style={{width: 300, height: 300}}/>
<TouchableHighlight
onPress={() => this.rotate(90)}
style={styles.button}
>
<Text style={styles.text}>ROTATE CW</Text>
</TouchableHighlight>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Here is My research and what i have found https://aboutreact.com/react-native-rotate-image-view-using-animation/
npm install -g react-native-cli
react-native init myproject
cd myproject
then .js
import React from 'react';
import { StyleSheet, View, Animated, Image, Easing } from 'react-native';
export default class App extends React.Component {
RotateValueKeeper: any;
constructor() {
super();
this.RotateValueKeeper = new Animated.Value(0);
}
componentDidMount() {
this.ImageRotateStarterFunction();
}
ImageRotateStarterFunction() {
this.RotateValueKeeper.setValue(0);
Animated.timing(this.RotateValueKeeper, {
toValue: 1,
duration: 3000,
easing: Easing.linear,
}).start(() => this.ImageRotateStarterFunction());
}
render() {
const MyRotateData = this.RotateValueKeeper.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg'],
});
return (
<View style={styles.container}>
<Animated.Image
style={{
width: 150,
height: 150,
transform: [{ rotate: MyRotateData }],
}}
source={{
uri:
'https://aboutreact.com/wp-content/uploads/2018/08/logo1024.png',
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#C2C2C2',
},
});
then
Android
react-native run-android
iOS
react-native run-ios

Use react-native-view-pdf shows blank view

I use react-native-view-pdf, React Native version is 0.59.5
https://github.com/rumax/react-native-PDFView
I just follow the tutorial but show blank screen.
I can't figure it out. I don't know why they are showing empty screens.
Step1:
npm install react-native-view-pdf --save
Step2:
react-native link react-native-view-pdf
Use the code and type react-native run-ios
App.js:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import PDFView from 'react-native-view-pdf/lib/index';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
const resources = {
file: Platform.OS === 'ios' ? 'downloadedDocument.pdf' : '/sdcard/Download/downloadedDocument.pdf',
url: 'https://www.ets.org/Media/Tests/TOEFL/pdf/SampleQuestions.pdf',
base64: 'JVBERi0xLjMKJcfs...',
};
type Props = {};
export default class App extends Component<Props> {
render() {
const resourceType = 'url';
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<PDFView
fadeInDuration={250.0}
style={{ flex: 1 }}
resource={'https://www.ets.org/Media/Tests/TOEFL/pdf/SampleQuestions.pdf'}
resourceType={resourceType}
onLoad={(event) => console.log(`PDF rendered from ${event}`)}
onError={(error) => console.log('Cannot render PDF', error)}
/>
<Text>Bottom text</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
Show black screen:
You can try below library it will help you to achieve and this is high ranked library
see here
Installation
npm library
npm install rn-fetch-blob --save
npm install react-native-pdf --save
react-native link rn-fetch-blob
react-native link react-native-pdf
Example
import React from 'react';
import { StyleSheet, Dimensions, View } from 'react-native';
import Pdf from 'react-native-pdf';
export default class PDFExample extends React.Component {
render() {
const source = {uri:'http://samples.leanpub.com/thereactnativebook-sample.pdf',cache:true};
//const source = require('./test.pdf'); // ios only
//const source = {uri:'bundle-assets://test.pdf'};
//const source = {uri:'file:///sdcard/test.pdf'};
//const source = {uri:"data:application/pdf;base64,..."};
return (
<View style={styles.container}>
<Pdf
source={source}
onLoadComplete={(numberOfPages,filePath)=>{
console.log(`number of pages: ${numberOfPages}`);
}}
onPageChanged={(page,numberOfPages)=>{
console.log(`current page: ${page}`);
}}
onError={(error)=>{
console.log(error);
}}
style={styles.pdf}/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
marginTop: 25,
},
pdf: {
flex:1,
width:Dimensions.get('window').width,
}
});
I've recently used this library and it is very good as expected.
Try this:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import PDFView from 'react-native-view-pdf/lib/index';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
const resources = {
file: Platform.OS === 'ios' ? 'downloadedDocument.pdf' : '/sdcard/Download/downloadedDocument.pdf',
url: 'https://www.ets.org/Media/Tests/TOEFL/pdf/SampleQuestions.pdf',
base64: 'JVBERi0xLjMKJcfs...',
};
type Props = {};
export default class App extends Component<Props> {
render() {
const resourceType = 'url';
return (
<View style={{flex: 1, witdth: '100%'}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<PDFView
fadeInDuration={250.0}
style={{ flex: 1 }}
resource={'https://www.ets.org/Media/Tests/TOEFL/pdf/SampleQuestions.pdf'}
resourceType={resourceType}
onLoad={(event) => console.log(`PDF rendered from ${event}`)}
onError={(error) => console.log('Cannot render PDF', error)}
/>
<Text>Bottom text</Text>
</View>
);