React native Animated undefined is not an object (evaluating 'u.stopTracking') - javascript

I'm having the following problem: "undefined is not an object (evaluating 'u.stopTracking')".
It happens when on Expo I update a props, I tried to use on componentWillReceiveProps, stopAnimation() and stopTracking(), but I could not.
Link expo: Here
To make the error appear, just click on the image of the central player.
Can someone give me a hand?
App:
import * as React from 'react';
import { Text, View, StyleSheet, ImageBackground } from 'react-native';
import { Constants } from 'expo';
import Album from './Album';
import Track from './Track';
const State = ['normal', 'transparent', 'big'];
export default class App extends React.Component {
constructor() {
super();
this.state = {
type: 0,
};
}
render() {
let { type } = this.state;
return (
<View style={styles.container}>
<ImageBackground
source={{
uri:
'https://i.pinimg.com/originals/62/6f/84/626f84c40696c1308a77fd8331e12b3e.jpg',
}}
imageStyle={{ borderRadius: 4 }}
style={{
alignItems: 'center',
justifyContent: 'center',
height: 400,
width: 400,
}}>
<Album
type={State[type]} //normal,transparent,big
title={Track.name}
artist={Track.artists[0].name}
cover={Track.album.images[0].url}
onPress={() => {
type = ++type % 3;
this.setState({ type });
}}
/>
</ImageBackground>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#fff',
},
});
Album:
import * as React from 'react';
import {
Text,
View,
StyleSheet,
ImageBackground,
Animated,
TouchableOpacity,
} from 'react-native';
const size = 40;
export default class Album extends React.Component {
constructor(props) {
super(props);
this.min = size / 4;
this.max = size / 2;
this.heightCenter = new Animated.Value(this.min);
this.heightLateral = new Animated.Value(size / 2);
/*this.state = {
heightCenter: new Animated.Value(this.min),
heightLateral: new Animated.Value(size / 2),
};*/
}
animateBar = (el, value) => {
var newValue = value == this.max ? this.min : this.max;
Animated.timing(el, {
toValue: value,
}).start(() => this.animateBar(el, newValue));
};
onPress = e => {
return this.props.onPress(e);
};
componentDidMount() {
console.log(this.heightCenter)
this.animateBar(this.heightCenter, this.min);
this.animateBar(this.heightLateral, this.max);
}
componentWillReceiveProps(nextProps) {
if (nextProps.type !== this.props.type) {
console.log('componentWillReceiveProps');
//this.state.heightCenter.stopAnimation();
//this.state.heightLateral.stopAnimation();
//Animated.stopTracking();
//Animated.timing(this.heightCenter).stopTracking();
//Animated.timing(this.heightLateral).stopTracking();
/*this.state.heightCenter.stopTracking();
this.state.heightLateral.stopTracking();
this.state.heightCenter.stopAnimation();
this.state.heightLateral.stopAnimation();*/
//this.heightCenter = {};
//this.heightLateral = null;
//this.heightCenter.stopTracking();
//this.heightLateral.stopTracking();
//this.state.heightCenter.stopAnimation();
//this.state.heightLateral.stopAnimation();
console.log(this.heightCenter)
}
}
componentDidUnmount() {
console.log('componentDidUnmount');
//Animated.timing(this.heightCenter).stop();
//Animated.timing(this.heightLateral).stop();
}
componentDidUpdate() {
this.animateBar();
}
render() {
let { type, title, artist, cover } = this.props;
let barWidthCenter = {
height: this.heightCenter,
};
let barWidthLateral = {
height: this.heightLateral,
};
if (type != 'normal' && type != 'transparent' && type != 'big')
type = 'transparent';
let backgroundColor =
type == 'normal' ? 'rgba(255,255,255,1)' : 'rgba(255,255,255,0.5)';
let color = type == 'normal' ? '#000' : '#fff';
if (type == 'big')
return (
<TouchableOpacity onPress={() => this.onPress()}>
<View
style={{
alignItems: 'center',
justifyContent: 'center',
}}>
<ImageBackground
source={{
uri: cover,
}}
imageStyle={{ borderRadius: 4 }}
style={{
flexDirection: 'row',
alignItems: 'flex-end',
justifyContent: 'flex-start',
height: 200,
width: 200,
}}>
<View
style={{
borderRadius: 4,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'rgba(0,0,0,0.3)',
padding: 5,
height: 40,
width: 40,
margin: 5,
}}>
<Animated.View
style={[
{
backgroundColor: 'rgba(255,255,255,1)',
width: 5,
borderRadius: 5 / 2,
margin: 2,
},
barWidthLateral,
]}
/>
<Animated.View
style={[
{
backgroundColor: 'rgba(255,255,255,1)',
width: 5,
borderRadius: 5 / 2,
margin: 2,
},
barWidthCenter,
]}
/>
<Animated.View
style={[
{
backgroundColor: 'rgba(255,255,255,1)',
width: 5,
borderRadius: 5 / 2,
margin: 2,
},
barWidthLateral,
]}
/>
</View>
</ImageBackground>
<View style={{ paddingLeft: 12, paddingRight: 12 }}>
<Text style={{ fontWeight: 'bold', color: '#fff' }}>{title}</Text>
<Text style={{ color: '#fff' }}>{artist}</Text>
</View>
</View>
</TouchableOpacity>
);
return (
<TouchableOpacity onPress={() => this.onPress()}>
<View
style={{
backgroundColor: backgroundColor,
flexDirection: 'row',
justifyContent: 'center',
borderRadius: 4,
padding: 4,
}}>
<ImageBackground
source={{
uri: cover,
}}
imageStyle={{ borderRadius: 4 }}
style={{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
height: size,
width: size,
}}>
<Animated.View
style={[
{
backgroundColor: 'rgba(255,255,255,1)',
width: 5,
borderRadius: 5 / 2,
margin: 2,
},
barWidthLateral,
]}
/>
<Animated.View
style={[
{
backgroundColor: 'rgba(255,255,255,1)',
width: 5,
borderRadius: 5 / 2,
margin: 2,
},
barWidthCenter,
]}
/>
<Animated.View
style={[
{
backgroundColor: 'rgba(255,255,255,1)',
width: 5,
borderRadius: 5 / 2,
margin: 2,
},
barWidthLateral,
]}
/>
</ImageBackground>
<View style={{ paddingLeft: 12, paddingRight: 12 }}>
<Text style={{ fontWeight: 'bold', color }}>{title}</Text>
<Text style={{ color }}>{artist}</Text>
</View>
</View>
</TouchableOpacity>
);
}
}

I see it's been a while you asked this question. I don't know how you solved this problem but I've had the same error:
"undefined is not an object (evaluating 'u.stopTracking')"
because of the code here:
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
elementPositionX: 0,
target: null,
marginLeft: new Animated.Value(0),
};
It was happening because I had put the Animated Value in the state. It should have defined out of the state, as a property of the component class, like this:
export default class App extends React.Component {
constructor(props) {
super(props);
this.marginLeft= new Animated.Value(0);
this.state = {
elementPositionX: 0,
target: null,
};
The documentation about Animated API is so poor, so I am not sure why but this solved my problem.
EDIT:
I have managed to place it in the state somehow, and it works without giving the former error. However, I need to use this code to change the animated value: this.state.marginLeft2.setValue(amount); and this is actually changing the state directly - without using .setState(). It doesn't seem good to me.

Related

Camera not displaying after reloading app or running npx react-native start for the 2nd time

I have implemented tensor-flow camera functionalities for pose detection on a website and then hosted it on netlify. Link: https://uactivsite-mobile.netlify.app/.Also github link of the same: https://github.com/viveksgonal/uactivsite/blob/main/src/App.js
I am using this as webview on react-native app. The first time the app builds perfectly and the camera starts. But whenever I try to reload it or run npx react-native start the second time, the camera never opens.
If anyone knows where I'm going wrong, it would be pleasure if you provide the solution. Thank you.
Code is attached below for the react-native app part:
/* eslint-disable react-native/no-inline-styles */
import React, { useRef, useState } from 'react';
const exercises = [
{
name: 'High Knees',
total: 20,
index: 0
},
{
name: 'Jumping Jacks',
total: 25,
index: 1
},
{
name: 'Squats',
total: 20,
index: 2
},
]
import WebView from 'react-native-webview'
import {
View,
StyleSheet,
Text,
Image,
TouchableWithoutFeedback,
Modal
} from 'react-native';
import { useNavigation } from '#react-navigation/native';
const ExerciseCamera = () => {
const webviewRef = useRef(null)
const navigation = useNavigation();
const [speed, setSpeed] = useState(0)
const [reps, setReps] = useState(0)
const ex = 1
function getInjectableJSMessage(message) {
return `
(function() {
window.dispatchEvent(new MessageEvent('message', {
data: ${JSON.stringify(message)}
}));
})();
`;
}
function onMessage(data) {
let val = JSON.parse(data.nativeEvent.data)
if (val.type === 'reps') {
setReps(val.data.rep)
if (val.data.speed !== 0) {
setSpeed(val.data.speed)
}
}
else if (val.type === 'completed') {
navigation.navigate('dashboard', {
screen: 'completeddailyexercise',
});
}
else {
console.log(val.data.rep)
}
}
function sendDataToWebView(msg) {
webviewRef.current.injectJavaScript(
getInjectableJSMessage(msg)
);
}
return (
<View style={styles.container}>
<Modal
transparent={true}
visible={true}
>
<View style={styles.top_container}>
<TouchableWithoutFeedback
onPress={() => {
navigation.navigate('dashboard', {
screen: 'completeddailyexercise',
});
}}>
<Image
style={styles.icons_container}
source={require('../../Assets/play.png')}
/>
</TouchableWithoutFeedback>
<View style={styles.exercise_name_container}>
<Text style={styles.exercise_name}>Side lunges</Text>
</View>
<TouchableWithoutFeedback
onPress={() => {
navigation.navigate('dashboard', { screen: 'dailychallange' });
}}>
<View style={styles.icons_container}>
<Image
style={styles.icon}
source={require('../../Assets/close.png')}
/>
</View>
</TouchableWithoutFeedback>
</View>
<View style={styles.bottom_container}>
<View style={styles.timer_container}>
<Text style={styles.timer_text}>02:47</Text>
</View>
{reps > 0 ? (
<View
style={[
styles.number_container,
{ justifyContent: speed > 0 ? 'space-between' : 'center' },
]}>
{speed > 0 ? <Text style={styles.number}>{speed} RS</Text> : null}
<Text style={styles.number}>{reps}/{exercises[ex].total}</Text>
</View>
) : null}
</View>
</Modal>
<WebView
ref={webviewRef}
mediaPlaybackRequiresUserAction={false}
source={{ uri: 'https://uactivsite-mobile.netlify.app/' }}
scalesPageToFit={false}
mixedContentMode="compatibility"
onMessage={onMessage}
onLoad={event => {
sendDataToWebView({
data: exercises[ex],
type: 'exercise'
})
}}
/>
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1 },
preview: {
flex: 1,
},
top_container: {
zIndex: 1,
position: 'absolute',
top: 43,
paddingHorizontal: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
width: '100%',
},
bottom_container: {
zIndex: 1,
position: 'absolute',
bottom: 0,
width: '100%',
},
number: { color: 'white', fontSize: 28 },
exercise_name_container: {
height: 40,
width: 155,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 20,
backgroundColor: 'rgba(255,255,255,0.2)',
},
number_container: {
height: 62,
backgroundColor: 'black',
width: '100%',
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 19,
},
timer_container: {
width: '100%',
height: 78,
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
backgroundColor: 'rgba(255,255,255,0.45)',
alignItems: 'center',
},
timer_text: { color: 'black', fontSize: 48, fontFamily: 'Poppins-Bold' },
icons_container: {
height: 40,
width: 40,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 50,
backgroundColor: 'rgba(255,255,255,0.8)',
},
icon: { width: 16, height: 16, resizeMode: 'contain' },
exercise_name: { color: 'black', fontFamily: 'Poppins-SemiBold', fontSize: 23 },
});
export default ExerciseCamera;

Making a function, call it with button click and update the view with results in react native

UPDATED CODE
This now fetches the data when button clicked but I cant display it as it did when it loaded first time?
I am totally new with react native so I am sorry if I explain my problem wrong or seem a little thick. I have made a screen that fetches data and displays the data and it seems to work quite well. However I have a couple of buttons and I want to add an onclick to call a function.
Maybe I am getting this wrong but its supposed to work like javascript which I have no problem with but I think I am missing something with the difference between components and functions.
For example in my code its just automatically fetches the data and displays it. How would I make functions to load the data when one the buttons is clicked and also update the view with the new loaded data?
I have tried putting the functions in with the fetch data but I seem to have to add everything but surely I can make re-usable functions for each task like I would in javascript.
I have included my code for the page and also what I have tried. Any help of advice would be great as when I am researching on the net I get confused information between reactjs and native.
Also all the code below has been snippets taken from various places and played around with so it is totally probably all wrong in terms of structure.
The code :
import React from "react";
import {
StyleSheet,
View,
ActivityIndicator,
FlatList,
Text,
StatusBar,
Image,
TouchableOpacity,
ScrollView,
SafeAreaView
} from "react-native";
import Icon from "react-native-vector-icons/Entypo";
import CupertinoButtonPurple1 from "../components/CupertinoButtonPurple1";
import Removebutton from "../components/removebutton";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
dataSource:[] };
}
componentDidMount(){
fetch("https://www.uberfantasies.com/testv2.php")
.then(response => response.json())
.then((responseData)=> {
this.setState({
loading: false,
dataSource: responseData.data
})
})
.catch(error=>console.log(error)) //to catch the errors if any
}
FlatListItemSeparator = () => {
return (
<View/>
);
}
renderItem=(data)=>
<SafeAreaView>
<View style={styles.container}>
<View style={styles.rect}>
<View style={styles.imageRow}>
<Image source={{uri: data.item.image}} style={styles.image} />
<View style={styles.group2Column}>
<View style={styles.group2}>
<Text style={styles.bitch}>
<Text>{data.item.from} sent you a mesage!</Text>
</Text>
<Text style={styles.loremIpsum}>
"{data.item.message}"
</Text>
</View>
<View style={styles.loremIpsum2Row}>
<Text style={styles.loremIpsum2}>{data.item.when}</Text>
<View style={styles.loremIpsum2Filler}></View>
<View style={styles.group3}>
<CupertinoButtonPurple1
style={styles.cupertinoButtonPurple1}
></CupertinoButtonPurple1>
<Removebutton
style={styles.removebutton}
></Removebutton>
</View>
</View>
</View>
</View>
</View>
</View>
</SafeAreaView>
render(){
if(this.state.loading){
return(
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9"/>
</View>
)}
return(
<View style={styles.container}>
<FlatList
data= {this.state.dataSource}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem= {item=> this.renderItem(item)}
keyExtractor= {item=>item.id.toString()}
/>
</View>
)}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
loader:{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
},
rect: {
height: 97,
backgroundColor: "rgba(230,230, 230,0.57)",
borderWidth: 0,
borderColor: "rgba(0,0,0,0.57)",
marginTop: 0,
borderBottomWidth: 1,
borderBottomColor: "#d5d5d5",
backgroundColor: "#f4f4f4"
},
image: {
width: 80,
height: 80,
borderRadius: 15,
borderWidth: 4,
borderColor: '#ffffff',
shadowColor: '#d5d5d5',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 2
},
group2: {
height: 41
},
bitch: {
fontFamily: "sans-serif-condensed",
color: "#121212",
fontSize: 14,
height: 17,
fontWeight: "bold",
marginTop: 2
},
loremIpsum: {
fontFamily: "sans-serif-condensed",
color: "#121212",
height: 17,
width: 159,
marginTop: 4
},
loremIpsum2: {
fontFamily: "sans-serif-condensed",
color: "#121212",
fontSize: 10,
marginTop: 8
},
loremIpsum2Filler: {
flex: 1,
flexDirection: "row"
},
group3: {
width: 125,
height: 26,
flexDirection: "row",
justifyContent: "space-between",
marginRight: 25
},
cupertinoButtonPurple1: {
height: 25,
width: 57
},
cupertinoButtonDanger2: {
height: 25,
width: 57
},
loremIpsum2Row: {
height: 26,
flexDirection: "row",
marginTop: 17,
marginRight: 33,
width: "100%"
},
group2Column: {
width: 275,
marginLeft: 16
},
imageRow: {
height: 84,
flexDirection: "row",
marginTop: 8,
marginLeft: 4
}
});
and the way I have tried to make a function and the way I think it should work with results?
The UPDATED code that fetches data but I cant get it to display data how it did in the previous code? Going out my nut here because I think Im missing something silly. If I had only one element to display or change I could do it but I think its because it looks through the results? Am i wrong?
Heres the code:
import React, { useState, Component } from 'react'
import {
StyleSheet,
View,
ActivityIndicator,
FlatList,
Text,
StatusBar,
Image,
TouchableOpacity,
ScrollView,
SafeAreaView
} from 'react-native'
class App extends Component {
state = {
loading: true,
dataSource:[],
Status: "Not loaded"
}
onPress = () => {
fetch("https://www.uberfantasies.com/testv.php")
.then(response => response.json())
.then((responseData)=> {
this.setState({
loading: false,
Status: "Loaded",
dataSource: responseData.data
})
console.log(this.state.dataSource)
})
.catch(error=>console.log(error)) //to catch the errors if any
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.button}
onPress={this.onPress}
>
<Text>Click me</Text>
</TouchableOpacity>
<View>
<Text>
Status : { this.state.Status }
</Text>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
marginBottom: 10
},
loader:{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
}
})
export default App;
if you want to call a function within onPress you need to call it. Like
<Button title="Press Me" onPress={() => ReloadData()} />
Below is a sample code snippet. I have used the function component as it is easy for a beginner. Assuming your output of the API call is a list, I am setting it to the state variable. SO whenever the 'apiData' variable value changes your component will re-render. You can user either a button or a touchable wrapper component for a clickable item.
const [apiData, setApiData] = useState([]);
const MySampleComponent = () => {
const apiCall = () => {
//Your code
setApiData(result);
};
const renderListItem = (itemData) => <Text>{itemData.item.<your key>}</Text>;
return (
<View>
<FlatList
keyExtractor={item => item.id}
data={apiData}
renderItem={renderListItem}
/>
<Button onPress={apiCall} />
<TouchableOpacity onPress={apiCall}>
<Text>Click Me</Text>
</TouchableOpacity>
</View>
);
};
Thanks for your comments and help, I think I have a much better way of understanding a few things now. I have managed to get a load button to fetch data and display it in the way as previously managed. I know it does not look like much progress but trust me this is a big step to getting to grips with the way things work for me.
Now time to play around with it, thanks again.
The working code (well best I can do at the minute!)
import React, { useState, Component } from 'react';
import {
StyleSheet,
View,
ActivityIndicator,
FlatList,
Text,
StatusBar,
Image,
TouchableOpacity,
ScrollView,
SafeAreaView,
} from 'react-native';
import Icon from 'react-native-vector-icons/Entypo';
import CupertinoButtonPurple1 from '../components/CupertinoButtonPurple1';
import CupertinoButtonDanger2 from '../components/CupertinoButtonDanger2';
class App extends Component {
state = {
loading: false,
dataSource: [],
Status: 'Not loaded',
};
componentDidMount() {
// this.onPress();
}
onPress = () => {
this.setState({
loading: true,
});
fetch('https://www.uberfantasies.com/testv.php')
.then((response) => response.json())
.then((responseData) => {
this.setState({
loading: false,
Status: 'Loaded',
dataSource: responseData.data,
});
console.log(this.state.dataSource);
})
.catch((error) => console.log(error)); //to catch the errors if any
};
FlatListItemSeparator = () => {
return <View />;
};
renderItem = (data) => (
<SafeAreaView>
<View style={styles.container}>
<View style={styles.rect}>
<View style={styles.imageRow}>
<Image source={{ uri: data.item.image }} style={styles.image} />
<View style={styles.group2Column}>
<View style={styles.group2}>
<Text style={styles.bitch}>
Bitch from Cov sent you a mesage!
</Text>
<Text style={styles.loremIpsum}>
"Hi there you Sexy Beast!"
</Text>
</View>
<View style={styles.loremIpsum2Row}>
<Text style={styles.loremIpsum2}>12 Feb 2022, 6.05 pm</Text>
<View style={styles.loremIpsum2Filler}></View>
<View style={styles.group3}>
<CupertinoButtonPurple1
style={
styles.cupertinoButtonPurple1
}></CupertinoButtonPurple1>
<CupertinoButtonDanger2
style={
styles.cupertinoButtonDanger2
}></CupertinoButtonDanger2>
</View>
</View>
</View>
</View>
</View>
</View>
</SafeAreaView>
);
render() {
if (this.state.loading) {
return (
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9" />
</View>
);
}
return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={this.onPress}>
<Text>Click me</Text>
</TouchableOpacity>
<View>
<Text>Status : {this.state.Status}</Text>
</View>
<FlatList
data={this.state.dataSource}
ItemSeparatorComponent={this.FlatListItemSeparator}
renderItem={(item) => this.renderItem(item)}
keyExtractor={(item) => item.id.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
marginBottom: 10,
},
loader: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
rect: {
height: 97,
backgroundColor: 'rgba(230,230, 230,0.57)',
borderWidth: 0,
borderColor: 'rgba(0,0,0,0.57)',
marginTop: 0,
borderBottomWidth: 1,
borderBottomColor: '#d5d5d5',
backgroundColor: '#f4f4f4',
},
image: {
width: 80,
height: 80,
borderRadius: 15,
borderWidth: 4,
borderColor: '#ffffff',
boxShadow: '0px 2px 4px 0px rgb(0 0 0 / 55%)',
},
group2: {
width: 275,
height: 41,
},
bitch: {
fontFamily: '-apple-system,Segoe UI,Roboto,sans-serif',
color: '#121212',
fontSize: 14,
height: 17,
fontWeight: 'bold',
marginTop: 2,
},
loremIpsum: {
fontFamily: '-apple-system,Segoe UI,Roboto,sans-serif',
color: '#121212',
height: 17,
width: 159,
marginTop: 4,
},
loremIpsum2: {
fontFamily: '-apple-system,Segoe UI,Roboto,sans-serif',
color: '#121212',
fontSize: 10,
marginTop: 8,
},
loremIpsum2Filler: {
flex: 1,
flexDirection: 'row',
},
group3: {
width: 121,
height: 26,
flexDirection: 'row',
justifyContent: 'space-between',
},
cupertinoButtonPurple1: {
height: 25,
width: 57,
},
cupertinoButtonDanger2: {
height: 25,
width: 57,
},
loremIpsum2Row: {
height: 26,
flexDirection: 'row',
marginTop: 17,
marginRight: 3,
},
group2Column: {
width: 275,
marginLeft: 16,
},
imageRow: {
height: 84,
flexDirection: 'row',
marginTop: 8,
marginLeft: 4,
},
});
export default App;

Which component should I use class or functional?

I'm trying to use react-native-camera and I want to send tokens from the first page to the camera page.
how can I get a token on the camera page? I am not sure how to solve this problem, I tried to change the camera page to function based component but I get more errors :) so I'd be very happy if you guys help me out
the first page is function-based component
import React from 'react';
import {View, Text, TouchableOpacity, ActivityIndicator} from 'react-native';
const first = () => {
const token = '12345678';
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
{isData?(
<TouchableOpacity
onPress={() => {
navigation.navigate('cameraV2', {token:token});
}}
style={{
height: 50,
width: '80%',
backgroundColor: '#f45f00',
alignItems: 'center',
justifyContent: 'center',
}}>
<Text style={{fontWeight: 'bold', fontSize: 18}}>
Giriş için tıklayın
</Text>
</TouchableOpacity>
):(
<ActivityIndicator size='large' color='#0f0' />
)}
</View>
);
};
export default first;
camera page is class based component
import React, {Component} from 'react';
import {Button, Text, View} from 'react-native';
import {RNCamera} from 'react-native-camera';
class cameraV2 extends Component {
navigation = this.props.navigation;
constructor(props) {
super(props);
this.camera = null;
this.barcodeCodes = [];
this.state = {
token:this.navigation.token,
is_camera: 0,
is_loading: 0,
barcodes: [],
camera: {
type: RNCamera.Constants.Type.back,
flashMode: RNCamera.Constants.FlashMode.auto,
},
};
}
barcodeRecognized = ({barcodes}) => {
barcodes.forEach(barcode => {
if(barcode.type!=='UNKNOWN_FORMAT'){
console.log(barcode.data)
this.setState({barcodes});
}
});
};
render() {
return (
<View style={styles.container}>
<RNCamera
ref={ref => {
this.camera = ref;
}}
defaultTouchToFocus
flashMode={this.state.camera.flashMode}
mirrorImage={false}
//onBarCodeRead={this.onBarCodeRead.bind(this)}
onGoogleVisionBarcodesDetected={this.barcodeRecognized}
onFocusChanged={() => {}}
onZoomChanged={() => {}}
permissionDialogTitle={'Permission to use camera'}
permissionDialogMessage={
'We need your permission to use your camera phone'
}
style={styles.preview}
type={this.state.camera.type}
/>
<View style={[styles.overlay, styles.topOverlay]}>
<Text style={styles.scanScreenMessage}>Please scan the barcode.</Text>
<Text style={styles.scanScreenMessage}>token: {this.state.token} </Text>
</View>
<View style={[styles.overlay, styles.bottomOverlay]}>
<Button
onPress={() =>
this.navigation.navigate('second', {
barcode: this.state.barcodes,
token: token,
})
}
style={styles.enterBarcodeManualButton}
title="Enter Barcode"
/>
</View>
</View>
);
}
}
const styles = {
container: {
flex: 1,
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
},
overlay: {
position: 'absolute',
padding: 16,
right: 0,
left: 0,
alignItems: 'center',
},
topOverlay: {
top: 0,
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
bottomOverlay: {
bottom: 0,
backgroundColor: 'rgba(0,0,0,0.4)',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
enterBarcodeManualButton: {
padding: 15,
backgroundColor: 'white',
borderRadius: 40,
},
scanScreenMessage: {
fontSize: 14,
color: 'white',
textAlign: 'center',
alignItems: 'center',
justifyContent: 'center',
},
};
export default cameraV2;
You just need to initialise the state with token value from route params obtained from props instead of navigation
this.state = {
token: this.props.route.params.token,
is_camera: 0,
is_loading: 0,
barcodes: [],
camera: {
type: RNCamera.Constants.Type.back,
flashMode: RNCamera.Constants.FlashMode.auto,
},
};
}
P.S You do not need to convert the entire component to functional
component just for using params

React functional bases props is not defined

i need your helps.
I have a functional based component call WelcomeSlidePage. I want to pass a functional to the functional component. i try to console.log the function in functional component, in the first state, console.log is printing the function, but after the second state, it's becomes undefine.
this is my component that calling the functional component
WebViewPage.jsx
<Modal transparent={true} visible={this.state.WelcomeSlidePageModal} animationType="
<WelcomeSlidePage onDone={()=>{console.log('test bro');this.setState({WelcomeSlidePageModal:false})}}/>
</Modal>
and this is my functional component
WelcomeSlidePage.jsx
import React, { useState, useEffect } from 'react';
import { StyleSheet, View, Text, Image, TouchableOpacity } from 'react-native';
import AppIntroSlider from 'react-native-app-intro-slider';
import string from '../string'
import { _storeData, _getData } from '../components/StoreAsync';
export default WelcomeSlide = (props) => {
const [language, setLanguage] = useState('english');
const [showRealApp, setShowRealApp] = useState(false);
const welcomeSlide = string.welcome_slide[language]
useEffect(() => {
console.log('testing bro',props.onDone)
// getData();
});
async function getData() {
setLanguage( await _getData("language"));
setShowRealApp( await _getData("showRealApp"));
}
_renderItem = ({ item }) => {
switch (item.key) {
case ('k4'):
return (
<View style={{backgroundColor : '#a0c83a', flex: 1}}>
<Text style={styles.title}>{item.title}</Text>
<View style={{justifyContent: 'center', paddingHorizontal: 20, flex: 1}}>
<Text style={styles.text}>{item.text_4_a}</Text>
<View style={{flexDirection: 'row'}}>
<Image style={styles.icon} source={item.icon} />
<Text style={{paddingStart: 5, paddingEnd: 20, ...styles.text}}>{item.text_4_b}</Text>
</View>
<Text style={styles.text}>{item.text_4_c}</Text>
<View style={{flexDirection: 'row'}}>
<Image style={styles.icon} source={item.icon} />
<Text style={{paddingStart: 5, paddingEnd: 20, ...styles.text}}>{item.text_4_d}</Text>
</View>
</View>
</View>
);
case ('k5'):
return (
<View style={styles.slide}>
<Text style={styles.title}>{item.text_5}</Text>
<TouchableOpacity style={{marginVertical: 24}} onPress={()=>{ props.navigation.navigate('WebView', { url: string.onboarding[language].login_url }); }}>
<Text style={styles.button}>{item.text_5_btn1}</Text>
</TouchableOpacity>
<TouchableOpacity style={{marginVertical: 24}} onPress={()=>{ props.navigation.navigate('WebView', { url: string.onboarding[language].register_url }); }}>
<Text style={styles.button}>{item.text_5_btn2}</Text>
</TouchableOpacity>
</View>
);
default:
return (
<View style={styles.slide}>
<Text style={styles.title}>{item.title}</Text>
<Image style={styles.image} source={item.image} />
<Text style={{paddingHorizontal: 20, ...styles.text}}>{item.text}</Text>
</View>
);
}
}
_onDone = () => {
setShowRealApp(true);
_storeData('isPassSlide',true);
props.navigation.navigate('WebView', { url: string.onboarding[language].login_url,splashScreen:false });
}
const slides = [
{
key: 'k1',
title: welcomeSlide.title,
text: welcomeSlide.a,
image: require('../images/my_library_card_white_notext_nopadding.png'),
backgroundColor: '#a0c83a',
},
{
key: 'k2',
title: welcomeSlide.title,
text: welcomeSlide.b,
image: require('../images/my_account_white_notext_nopadding.png'),
backgroundColor: '#a0c83a',
},
{
key: 'k3',
title: welcomeSlide.title,
text: welcomeSlide.c,
image: require('../images/library_catalog_white_notext_nopadding.png'),
backgroundColor:'#a0c83a',
},
{
key: 'k4',
title: welcomeSlide.title,
text_4_a: welcomeSlide.d_a,
text_4_b: welcomeSlide.d_b,
text_4_c: welcomeSlide.d_c,
text_4_d: welcomeSlide.d_d,
icon: require('../images/icon-hand-right.png'),
backgroundColor: '#a0c83a',
},
{
key: 'k5',
text_5: welcomeSlide.e,
text_5_btn1: welcomeSlide.e_btn1,
text_5_btn2: welcomeSlide.e_btn2,
backgroundColor:'#a0c83a',
},
];
return(
<AppIntroSlider
renderItem={_renderItem}
prevLabel={string.back[language]}
nextLabel={string.next[language]}
doneLabel={string.next[language]}
showPrevButton={true}
slides={slides}
onDone={()=>props.onDone()}/>
)
}
const styles = StyleSheet.create({
slide : {
flex: 1,
paddingTop: (Platform.OS) === 'ios' ? 20 : 0,
paddingBottom: 80,
backgroundColor : '#a0c83a',
alignItems: 'center',
},
title: {
fontSize: 24,
color: '#fff',
fontWeight: 'bold',
textAlign: 'center',
marginTop : 30,
},
text: {
fontSize : 20,
color: '#fff',
textAlign: 'left',
},
image: {
width: 200,
height: 200,
resizeMode: 'contain',
flex:1,
},
icon: {
top: 10,
width: 25,
height: 15,
width: 25,
marginTop: -3,
},
content: {
paddingHorizontal: 20,
},
button: {
borderRadius: 8,
paddingVertical: 12,
paddingHorizontal: 12,
color: 'white',
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginHorizontal: 40,
backgroundColor: '#e46825',
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.8,
shadowRadius: 2,
elevation: 5,
},
});
and then this is the console log
testing bro function onDone() {
console.log('test bro');
_this2.setState({
WelcomeSlidePageModal: false
});
} b11b05fa-4e76-41da-9d58-218edc178e45:157683:15
testing bro undefined
please help me guys, thanks

Unable to navigate to a different component on button click - React-Native Navigator

var
{Text,View,TextInput,TouchableWithoutFeedback,Image,ToastAndroid,Platform,NavigatorIOS,Navigator} = React;
var MainActivity = require('./MainActivity');
class LoginScreen extends React.Component {
Login(){
return <Navigator
initialRoute={{name: 'MainActivity', component: MainActivity, index: 0}}
renderScene={(route, navigator) => {
return React.createElement(<MainActivity />);
}} />
}
I am trying to make this work. After clicking on login button, it should go to the main activity. So LoginScreen.js onClick MainActivity.js.
My github project for you to check for more reference. Please help.
I just looked at your code. It looks like you need to set up your initial route as a navigator component. I've fixed it and am pasting the code below. The two files that need to be fixed are index.ios.js, and LoginScreen.js.:
index.ios.js
'use strict';
var React = require('react-native');
var {Text,View,TextInput,Navigator, Navigator} = React;
var LoginScreen = require('./LoginScreen');
var MainActivity = require('./MainActivity');
class Trabble extends React.Component {
render() {
return (
<Navigator
style={{flex:1}}
initialRoute={{name: 'LoginScreen', component: LoginScreen, index: 0}}
renderScene={(route, navigator) => {
return React.createElement(route.component, {navigator});
}} />
)
}
}
var Styles = React.StyleSheet.create({
loginText: {
fontSize: 50,
color: "blue",
marginTop: 100,
alignSelf: "center"
},
usernameText: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
marginTop: 10
},
passwordText: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
marginTop: 10
}
});
React.AppRegistry.registerComponent('Trabble', function() { return Trabble });
LoginScreen.js:
'use strict';
var React = require('react-native');
var {Text,View,TextInput,TouchableWithoutFeedback,Image,ToastAndroid,Platform,NavigatorIOS,Navigator} = React;
var MainActivity = require('./MainActivity');
class LoginScreen extends React.Component {
login() {
this.props.navigator.push({
component: MainActivity
})
}
render() {
return(
<View style={styles.loginView}>
<Image style={styles.image} source={require('./Ionic.png')}/>
<Text style={styles.loginText}>Chat System</Text>
<TextInput style={styles.usernameText} placeholder="username" placeholderTextColor="black"></TextInput>
<TextInput style={styles.passwordText} placeholder="password" placeholderTextColor="black" secureTextEntry></TextInput>
<TouchableWithoutFeedback onPress={ () => this.login() }>
<View style={styles.loginButton}>
<Text style={styles.loginButtonText}>Smit is smart</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback>
<View style={styles.signUpButton}>
<Text style={styles.signUpButtonText}>Sign Up</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={ () => this.login() }>
<View>
<Text style={styles.forgetPasswordText}>Forgot password?</Text>
</View>
</TouchableWithoutFeedback>
</View>)
}
}
var styles = React.StyleSheet.create({
image:{
height: 150,
alignSelf: "center",
marginTop: 50,
opacity: 1
},
loginView:{
backgroundColor: "#FA8A3A",
flex: 1
},
loginText: {
fontSize: 50,
color: "white",
marginTop: 10,
alignSelf: "center"
},
usernameText: {
height: 40,
color: 'black',
borderColor: 'gray',
borderWidth: 1,
marginTop: 10
},
passwordText: {
height: 40,
borderColor: 'gray',
borderWidth: 1,
marginTop: 10
},
loginButtonText:{
alignSelf: 'center',
fontSize: 20,
color: 'white'
},
loginButton:{
marginTop: 10,
height: 30,
backgroundColor: 'blue'
},
signUpButtonText:{
alignSelf: 'center',
fontSize: 20,
color: 'white'
},
signUpButton:{
marginTop: 10,
height: 30,
backgroundColor: 'grey'
},
forgetPasswordText:{
fontSize: 10,
alignSelf: 'center',
marginTop: 10
}
});
module.exports = LoginScreen;
I've also submitted a pull request to you with the fixed code.

Categories

Resources