QRCode scanner issue with react-native-camera - ios

I use ReactNative to develop my iOS APP,to realize the QRCode scanner function,i took the react-native-camera component which provide the barcode scanner function to my project.everything goes all right,but when i had succeed in recognizing a QRCode,next time i use the model,the screen just got frozen,seems like the app goes crashed. something interesting that as the screen is frozen,and once the model cancelled from the left button of navigation,The module can work properly.
I'm not sure whether it's a inner bug of NavigatorIOS,or just the bug of react-native-camera itself.
here is the QRCode component code:
'use strict';
var React = require('react-native');
var Dimensions = require('Dimensions');
var {
StyleSheet,
View,
Text,
TouchableOpacity,
VibrationIOS,
Navigator,
} = React;
var Camera = require('react-native-camera');
var { width, height } = Dimensions.get('window');
var QRCodeScreen = React.createClass({
propTypes: {
cancelButtonVisible: React.PropTypes.bool,
cancelButtonTitle: React.PropTypes.string,
onSucess: React.PropTypes.func,
onCancel: React.PropTypes.func,
},
getDefaultProps: function() {
return {
cancelButtonVisible: false,
cancelButtonTitle: 'Cancel',
barCodeFlag: true,
};
},
_onPressCancel: function() {
var $this = this;
requestAnimationFrame(function() {
$this.props.navigator.pop();
if ($this.props.onCancel) {
$this.props.onCancel();
}
});
},
_onBarCodeRead: function(result) {
var $this = this;
if (this.props.barCodeFlag) {
this.props.barCodeFlag = false;
setTimeout(function() {
VibrationIOS.vibrate();
$this.props.navigator.pop();
$this.props.onSucess(result.data);
}, 1000);
}
},
render: function() {
var cancelButton = null;
if (this.props.cancelButtonVisible) {
cancelButton = <CancelButton onPress={this._onPressCancel} title={this.props.cancelButtonTitle} />;
}
return (
<Camera onBarCodeRead={this._onBarCodeRead} style={styles.camera}>
<View style={styles.rectangleContainer}>
<View style={styles.rectangle}/>
</View>
{cancelButton}
</Camera>
);
},
});
var CancelButton = React.createClass({
render: function() {
return (
<View style={styles.cancelButton}>
<TouchableOpacity onPress={this.props.onPress}>
<Text style={styles.cancelButtonText}>{this.props.title}</Text>
</TouchableOpacity>
</View>
);
},
});
var styles = StyleSheet.create({
camera: {
width:width,
height: height,
alignItems: 'center',
justifyContent: 'center',
},
rectangleContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'transparent',
},
rectangle: {
height: 250,
width: 250,
borderWidth: 2,
borderColor: '#00FF00',
backgroundColor: 'transparent',
},
cancelButton: {
flexDirection: 'row',
justifyContent: 'center',
backgroundColor: 'white',
borderRadius: 3,
padding: 15,
width: 100,
marginBottom: 10,
},
cancelButtonText: {
fontSize: 17,
fontWeight: '500',
color: '#0097CE',
},
});
module.exports = QRCodeScreen;
And In another Component I push this qrCode to the new sence:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
NavigatorIOS,
AlertIOS,
Navigator,
} = React;
var QRCodeScreen = require('./QRCodeScreen');
var cameraApp = React.createClass({
render: function() {
return (
<NavigatorIOS
style={styles.container}
initialRoute={{
title: 'Index',
backButtonTitle: 'Back',
component: Index,
}}
/>
);
}
});
var Index = React.createClass({
render: function() {
return (
<View style={styles.contentContainer}>
<TouchableOpacity onPress={this._onPressQRCode}>
<Text>Read QRCode</Text>
</TouchableOpacity>
</View>
);
},
_onPressQRCode: function() {
this.props.navigator.push({
component: QRCodeScreen,
title: 'QRCode',
passProps: {
onSucess: this._onSucess,
},
});
},
// onPressCancel:function(){
//
// this.props.navigator.getContext(this).pop();
//
// },
_onSucess: function(result) {
AlertIOS.alert('Code Context', result, [{text: 'Cancel', onPress: ()=>console.log(result)}]);
// console.log(result);
},
});
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
contentContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}
});
AppRegistry.registerComponent('Example', () => cameraApp);
Any answer will be helpful!

I think it's a inner bug of NavigatorIOS, or maybe just sth else wrong.
Blew is my code, it is ok.
'use strict';
const React = require('react-native');
const {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
Navigator,
} = React;
var QRCodeScreen = require('./QRCodeScreen');
const CameraApp = () => {
const renderScene = (router, navigator) => {
switch (router.name) {
case 'Index':
return <Index navigator={navigator}/>;
case 'QRCodeScreen':
return <QRCodeScreen
onSucess={router.onSucess}
cancelButtonVisible={router.cancelButtonVisibl}
navigator={navigator}
/>;
}
}
return (
<Navigator
style={styles.container}
initialRoute={{
name: 'Index',
}}
renderScene={renderScene}
/>
);
};
const Index = ({navigator}) => {
const onPressQRCode = () => {
navigator.push({
name: 'QRCodeScreen',
title: 'QRCode',
onSucess: onSucess,
cancelButtonVisible: true,
});
};
const onSucess = (result) => {
console.log(result);
};
return (
<View style={styles.contentContainer}>
<TouchableOpacity onPress={onPressQRCode}>
<Text>Read QRCode</Text>
</TouchableOpacity>
</View>
);
};
module.exports = CameraApp;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
contentContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}
});

you can try Library react native qrcode
https://github.com/moaazsidat/react-native-qrcode-scanner. on me ,
its run. you can try . in ios and android.

Related

Custom map marker showing on android device but not on iOS

I'm building a cross-platform app in React Native Expo, and am using react-native-maps to render a map with custom markers. I'm using the 'icon' prop on the Marker component to render a png image, and in addition to this, the Marker displays a child Text element, as follows:
<Marker
key={i}
coordinate={{
latitude: gig.location.latitude,
longitude: gig.location.longitude,
}}
icon={require('../assets/map-pin-50pc.png')}
onPress={() => {
navigation.navigate("GigDetails", {
venue: gig.venue,
gigName: gig.gigName,
image: gig.image,
blurb: gig.blurb,
isFree: gig.isFree,
genre: gig.genre,
dateAndTime: { ...gig.dateAndTime },
tickets: gig.tickets,
});
}}
>
<Text style={styles.gigInfo_text}>{gig.genre}</Text>
</Marker>
On android devices, the custom marker image and the text are rendered as expected. On iOS devices however, only the text is rendered, and the 'icon' image cannot be seen. Any suggestions as to why?
I tried importing the image and passing it to the icon prop as follows:
import mapPinImage from '../assets/map-pin-50pc.png'
...
...
icon = {mapPinImage}
This didn't work either. I also checked the size of the image which was 41x62 pixels, with a size of 2.41kb - well below apple's maximum size requirements.
For context, here's the entire component that render the map:
import { FC } from "react";
import { useState, useMemo } from "react";
import {
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
Platform,
Dimensions
} from "react-native";
import MapView from "react-native-maps";
import { Marker } from "react-native-maps";
import { mapStyle } from "../util/mapStyle";
import { useGigs } from "../hooks/useGigs";
import { AntDesign } from "#expo/vector-icons";
import { format } from "date-fns";
import { mapProps } from "../routes/homeStack";
import { Switch } from 'react-native-paper'
import mapPinImage from '../assets/map-pin-50pc.png'
type MapScreenNavgationProp = mapProps['navigation']
interface Props {
navigation: MapScreenNavgationProp
}
const GigMap:FC<Props> = ({ navigation }):JSX.Element => {
const [selectedDateMs, setSelectedDateMs] = useState<number>(Date.now());
const [isSwitchOn, setIsSwitchOn] = useState(false);
const gigs = useGigs();
//generates current date in format DD/MM/YYYY
const selectedDateString:string = useMemo(() => {
const formattedDate = format(new Date(selectedDateMs),'EEE LLL do Y')
return formattedDate
}, [selectedDateMs]);
const currentDay:string = useMemo(() => {
const formattedDay = format(new Date(selectedDateMs),'EEEE')
return formattedDay
},[selectedDateMs])
const currentWeek:string = useMemo(() => {
const formattedDay = format(new Date(selectedDateMs),'LLLL do Y')
return formattedDay
},[selectedDateMs])
//Filtering through gigs to return only current day's gigs
const gigsToday = gigs.filter((gig) => {
const formattedGigDate = format(new Date(gig.dateAndTime.seconds * 1000), 'EEE LLL do Y')
return formattedGigDate === selectedDateString;
});
const freeGigsToday = gigsToday.filter((gig) => {
return gig.isFree === true
})
const gigsToDisplay = isSwitchOn ? freeGigsToday : gigsToday
//increments date by amount
const addDays = (amount:number):void => {
setSelectedDateMs((curr) => curr + 1000 * 60 * 60 * 24 * amount);
};
const onToggleSwitch = () => setIsSwitchOn(!isSwitchOn);
return (
<View style={styles.container}>
<View testID="gigMapHeader" style={styles.headerText}>
<Text style={styles.headerText_main}>{currentDay}</Text>
<Text style={styles.headerText_sub}>{currentWeek}</Text>
</View>
<View style={styles.imageText}>
<Text style={styles.subHeader}>Tap on the</Text>
<Image
style={styles.image}
source={require("../assets/map-pin-new.png")}
/>
<Text style={styles.subHeader}>
icons on the map to see more gig info
</Text>
</View>
<View style={styles.mapContainer}>
<MapView
initialRegion={{
latitude: -41.29416,
longitude: 174.77782,
latitudeDelta: 0.03,
longitudeDelta: 0.03,
}}
style={styles.map}
customMapStyle={mapStyle}
>
{gigsToDisplay.map((gig, i) => {
return (
<Marker
key={i}
coordinate={{
latitude: gig.location.latitude,
longitude: gig.location.longitude,
}}
icon={require('../assets/map-pin-50pc.png')}
onPress={() => {
navigation.navigate("GigDetails", {
venue: gig.venue,
gigName: gig.gigName,
image: gig.image,
blurb: gig.blurb,
isFree: gig.isFree,
genre: gig.genre,
dateAndTime: { ...gig.dateAndTime },
tickets: gig.tickets,
});
}}
>
<Text style={styles.gigInfo_text}>{gig.genre}</Text>
</Marker>
);
})}
</MapView>
</View>
<View style={styles.buttonOptions}>
<TouchableOpacity onPress={() => addDays(-1)} style={styles.touchable}>
<AntDesign name="caretleft" size={36} color="#000000" />
<Text style={{ fontFamily: "NunitoSans", color: "#000000",marginLeft:'8%' }}>
Previous day
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => addDays(1)} style={styles.touchable}>
<AntDesign name="caretright" size={36} color="#000000" />
<Text style={{ fontFamily: "NunitoSans", color: "#000000",marginRight:'8%' }}>
Next day
</Text>
</TouchableOpacity>
</View>
<View style = {styles.buttonAndSwitch}>
<TouchableOpacity
onPress={() => navigation.navigate("List")}
style={styles.button}
>
<Text style={styles.buttonText}>List View</Text>
</TouchableOpacity>
<View style = {styles.switch}>
<Switch value={isSwitchOn} onValueChange={onToggleSwitch} color = '#377D8A' />
<Text style = {styles.switch_text}>Free Events</Text>
</View>
</View>
</View>
);
};
const {width:screenWidth, height:screenHeight} = Dimensions.get('window')
const mapWidth = screenWidth * 0.9 //this sets width to 90%
const mapHeight = mapWidth /0.91 //this set height based on the figma map aspect ratio of 0.91
const styles = StyleSheet.create({
container: {
// flexDirection: "column",
// alignItems: "center",
flex:1
},
map: {
height: '100%',
width: '100%'
},
mapContainer:{
marginTop: '5%',
marginHorizontal: 20,
width: mapWidth,
height: mapHeight,
flex:1,
...Platform.select({
ios: {
borderRadius:26,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.3,
shadowRadius: 2,
},
android: {
overflow: 'hidden',
borderRadius:26,
elevation: 4,
}
})
},
gigInfo: {
// backgroundColor: '#68912b',
// marginTop:20
},
gigInfo_text: {
fontSize:10,
color:'black',
fontFamily:'NunitoSans',
paddingTop: 25,
textAlign:'center',
fontWeight:'bold'
},
gigInfo_text_genre: {
color: "white",
fontFamily: "Helvetica-Neue",
transform: [{ translateY: -5 }],
},
headerText: {
color: "black",
fontSize: 25,
marginTop: '0%',
marginLeft: '7%',
fontFamily: "NunitoSans",
marginBottom: 10,
},
headerText_main: {
fontFamily: "NunitoSans",
fontSize:25,
lineHeight:34.1
},
headerText_sub: {
fontFamily:'LatoRegular',
size:14,
lineHeight:16.8
},
callout: {
width: "auto",
height: "auto",
backgroundColor: "azure",
},
buttonOptions: {
flexDirection: "row",
justifyContent: "space-between",
marginTop:'4%',
width:'100%'
},
buttonOptionsText: {
margin: 5,
},
image: {
height:20,
width:14,
marginHorizontal:3
},
imageText: {
flexDirection: "row",
marginLeft:'7%',
marginTop:27
},
touchable: {
flexDirection: "column",
alignItems: "center",
},
subHeader: {
fontFamily: "LatoRegular",
color: "#747474",
size: 12,
lineHeight: 17.04
},
button:{
flexDirection:'column',
width:115,
height:37,
marginLeft:'7%',
backgroundColor:'#377D8A',
borderRadius:8,
justifyContent:'center',
marginTop:'6%'
},
buttonText: {
color:'#FFFFFF',
textAlign:'center',
fontFamily: 'NunitoSans',
fontSize:16,
lineHeight:22
},
buttonAndSwitch:{
flexDirection:'row',
alignItems:'center',
justifyContent:'space-between'
},
switch:{
marginRight:'6%',
transform: [{translateY:7}]
},
switch_text: {
fontFamily: 'LatoRegular',
fontSize:10,
transform:[{translateY:-10}]
}
});
export default GigMap;
Try to replace icon image data props with image Icon as child component to Marker.
<Marker
key={i}
coordinate={{
latitude: gig.location.latitude,
longitude: gig.location.longitude,
}}
icon={require("../assets/map-pin-50pc.png")}
onPress={() => {
navigation.navigate("GigDetails", {
venue: gig.venue,
gigName: gig.gigName,
image: gig.image,
blurb: gig.blurb,
isFree: gig.isFree,
genre: gig.genre,
dateAndTime: { ...gig.dateAndTime },
tickets: gig.tickets,
});
}}
>
<Image
source={require("../assets/map-pin-50pc.png")}
style={{ width: 40, height: 40 }}
/>
<Callout>
<Text style={styles.gigInfo_text}>{gig.genre}</Text>
</Callout>
</Marker>

How to stop echo in iOS side react native audio-record-player?

Below my code for playing voice clip I send here from previous screen
import * as Progress from 'react-native-progress';
import { FontFamily, Fonts } from '../../common/GConstants';
import { Image, SafeAreaView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import React, { Component } from 'react';
import { heightPercentageToDP as hp, widthPercentageToDP as wp } from 'react-native-responsive-screen';
import AudioRecorderPlayer from 'react-native-audio-recorder-player';
import Colors from '../../common/GColors';
import GColors from '../../common/GColors';
import KeepAwake from 'react-native-keep-awake';
import WaveForm from 'react-native-audiowaveform';
import images from '../../assets/images/index';
import { secondsToTime } from '../../common/GFunction';
export default class ConfirmRecording extends Component {
constructor() {
super();
this.state = {
recordTime: '',
duration: '',
isPlaying: false,
totalDuration: '',
audioPath: '',
currentPositionSec: '',
currentDurationSec: '',
};
this.audioRecorderPlayer = new AudioRecorderPlayer();
}
showProgress = () => {
if (this.state.currentPositionSec / this.state.totalDuration > 1) {
return Math.round(
this.state.currentPositionSec / this.state.totalDuration,
);
} else {
return Math.fround(
this.state.currentPositionSec / this.state.totalDuration,
);
}
};
onStartPlay = async () => {
console.log('START and is playing', this.state.audioPath + "--------" + this.state.isPlaying);
if (this.state.isPlaying) {
this.setState({ isPlaying: false });
this.audioRecorderPlayer.stopPlayer();
this.audioRecorderPlayer.removePlayBackListener();
} else {
const msg = await this.audioRecorderPlayer.startPlayer(
this.state.audioPath,
// 'http://podcasts.cnn.net/cnn/services/podcasting/specials/audio/2007/05/milesobrien.mp3',
);
console.log('Play MSG', msg);
this.audioRecorderPlayer.addPlayBackListener((e) => {
this.setState({
isPlaying: true,
currentPositionSec: Math.round(
Math.round(Math.round(e.current_position / 10) / 100),
),
currentDurationSec: Math.round(Math.round(e.duration / 10) / 100),
playTime: e.current_position,
duration: e.duration,
});
if (e.duration == e.current_position) {
this.setState({ isPlaying: false });
console.log('Stopped');
this.audioRecorderPlayer.stopPlayer();
this.audioRecorderPlayer.removePlayBackListener();
}
return;
});
}
};
componentDidMount = () => {
var audioPath = this.props.navigation.getParam('audioPath');
var duration = this.props.navigation.getParam('duration');
console.warn("Data from prevciouyas screen", audioPath + "--------" + duration)
this.setState({
audioPath: audioPath,
duration: duration
});
}
componentWillUnmount = () => {
this.audioRecorderPlayer.stopPlayer();
this.audioRecorderPlayer.removePlayBackListener();
this.setState({
audioPath: '',
isPlaying: false
});
}
render() {
return (
<SafeAreaView style={style.mainContainer}>
<View style={style.audioView}>
<Text style={style.audioViewText}>Confirm Recording</Text>
<View style={{ marginTop: hp(2) }}>
<View style={style.secondWaveView}>
<WaveForm
style={style.WaveForm}
source={{ uri: this.state.audioPath }} // not work
stop={this.state.isPlaying}
play={this.state.isPlaying}
// autoPlay={true}
waveFormStyle={{ waveColor: Colors.gray, scrubColor: Colors.darkBlue }}
/>
<Text> {secondsToTime(this.state.currentPositionSec)
.m.toString()
.padStart(2, 0) +
':' +
secondsToTime(this.state.currentPositionSec)
.s.toString()
.padStart(2, 0)}</Text>
</View>
<View style={style.secondAudioView}>
<TouchableOpacity
onPress={(event) => {
this.audioRecorderPlayer.stopPlayer();
this.audioRecorderPlayer.removePlayBackListener();
this.setState({ audioPath: '', isPlaying: false }, () => {
// add Imerssion
// this.props.navigation.state.params.a(true),
this.props.navigation.navigate('ImpressionPro')
});
}
}
activeOpacity={.9}>
<Image source={images.sendIcon} />
</TouchableOpacity>
<View style={{ flex: 1 }} />
<TouchableOpacity style={style.icon}
onPress={() => {
this.audioRecorderPlayer.stopPlayer();
this.audioRecorderPlayer.removePlayBackListener();
this.setState({ audioPath: '', isPlaying: false }, () => {
this.props.navigation.pop(2)
});
}}
activeOpacity={.9}>
<Image source={images.deleteCancelBtn} />
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.onStartPlay()
.then(() => {
console.log('Playing');
})
.catch((err) => {
console.log('PErr', err);
});
}}
style={style.icon} activeOpacity={.9}>
<Image source={images.playBtn} />
</TouchableOpacity>
</View>
</View>
</View>
<KeepAwake />
</SafeAreaView>
)
}
}
const style = StyleSheet.create({
mainContainer:
{
flex: 1,
backgroundColor: Colors.darkBlue,
justifyContent: 'center',
alignItems: 'center'
},
secondWaveView:
{
marginTop: hp(2),
marginHorizontal: wp(5.5),
flexDirection: 'row',
justifyContent: 'space-between',
},
secondAudioView:
{
flexDirection: 'row',
marginTop: hp(2),
marginStart: wp(5)
},
WaveForm:
{
height: 25,
flex: 1,
},
icon:
{
marginEnd: wp(5)
},
audioView:
{
backgroundColor: Colors.white,
height: "25%",
width: "88%",
alignSelf: 'center',
borderRadius: hp(2),
},
audioViewText:
{
textAlign: 'center',
marginTop: hp(2),
fontSize: Fonts.fontsize20,
marginHorizontal: wp(6),
fontFamily: FontFamily.medium,
color: Colors.textCoffeeColor
},
})
issue was in the waveform for echo ... both were playing same time so thats why issue generated...

Add tabs into a React Native Maps

I want to add tabs at the bottom of my home screen but I don't manage how to do it.
I want two tabs like "Map" (for my homepage) and "Settings". I don't know how to create that, I tried to add some codes inside but it's not working. Do you have ideas of what I'm doing wrong?
Do I need to add these codes inside ?
class HomeScreen extends React.Component {
render() {
return (
class SettingsScreen extends React.Component {
render() {
return (
I also tried to add this code at the bottom:
const TabNavigator = createBottomTabNavigator({
MAP: { screen: HomeScreen },
SETTINGS: { screen: SettingsScreen },
});
export default createAppContainer(TabNavigator);
Here is my code:
import React, { Component } from 'react';
import { StyleSheet, Text, View, Animated, Image, Dimensions } from "react-native";
import { Components, MapView } from 'expo';
const Images = [
{ uri: "https://images.unsplash.com/photo-1555706655-6dd427c11735?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" },
{ uri: "https://images.unsplash.com/photo-1555706741-8f39aa887cf7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" },
{ uri: "https://images.unsplash.com/photo-1555706741-fade7dd756a9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" },
{ uri: "https://images.unsplash.com/photo-1555706742-67a1170e528d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" }
]
const { width, height } = Dimensions.get("window");
const CARD_HEIGHT = height / 5;
const CARD_WIDTH = CARD_HEIGHT - 50;
export default class screens extends Component {
state = {
markers: [
{
coordinate: {
latitude: 41.414494,
longitude: 2.152695,
},
title: "Parc Güell",
description: "One of the best view in Barcelona. ",
image: Images[0],
},
{
coordinate: {
latitude: 41.403706,
longitude: 2.173504,
},
title: "Sagrada Familia",
description: "This is the second best place in Portland",
image: Images[1],
},
{
coordinate: {
latitude: 41.395382,
longitude: 2.161961,
},
title: "Casa Milà",
description: "This is the third best place in Portland",
image: Images[2],
},
{
coordinate: {
latitude: 41.381905,
longitude: 2.178185,
},
title: "Gothic Quarter",
description: "This is the fourth best place in Portland",
image: Images[3],
},
],
region: {
latitude: 41.390200,
longitude: 2.154007,
latitudeDelta: 0.04864195044303443,
longitudeDelta: 0.040142817690068,
},
};
componentWillMount() {
this.index = 0;
this.animation = new Animated.Value(0);
}
componentDidMount() {
// We should detect when scrolling has stopped then animate
// We should just debounce the event listener here
this.animation.addListener(({ value }) => {
let index = Math.floor(value / CARD_WIDTH + 0.3); // animate 30% away from landing on the next item
if (index >= this.state.markers.length) {
index = this.state.markers.length - 1;
}
if (index <= 0) {
index = 0;
}
clearTimeout(this.regionTimeout);
this.regionTimeout = setTimeout(() => {
if (this.index !== index) {
this.index = index;
const { coordinate } = this.state.markers[index];
this.map.animateToRegion(
{
...coordinate,
latitudeDelta: this.state.region.latitudeDelta,
longitudeDelta: this.state.region.longitudeDelta,
},
350
);
}
}, 10);
});
}
render() {
const interpolations = this.state.markers.map((marker, index) => {
const inputRange = [
(index - 1) * CARD_WIDTH,
index * CARD_WIDTH,
((index + 1) * CARD_WIDTH),
];
const scale = this.animation.interpolate({
inputRange,
outputRange: [1, 2.5, 1],
extrapolate: "clamp",
});
const opacity = this.animation.interpolate({
inputRange,
outputRange: [0.35, 1, 0.35],
extrapolate: "clamp",
});
return { scale, opacity };
});
return (
<View style={styles.container}>
<MapView
ref={map => this.map = map}
initialRegion={this.state.region}
style={styles.container}
>
{this.state.markers.map((marker, index) => {
const scaleStyle = {
transform: [
{
scale: interpolations[index].scale,
},
],
};
const opacityStyle = {
opacity: interpolations[index].opacity,
};
return (
<MapView.Marker key={index} coordinate={marker.coordinate}>
<Animated.View style={[styles.markerWrap, opacityStyle]}>
<Animated.View style={[styles.ring, scaleStyle]} />
<View style={styles.marker} />
</Animated.View>
</MapView.Marker>
);
})}
</MapView>
<Animated.ScrollView
horizontal
scrollEventThrottle={1}
showsHorizontalScrollIndicator={false}
snapToInterval={CARD_WIDTH}
onScroll={Animated.event(
[
{
nativeEvent: {
contentOffset: {
x: this.animation,
},
},
},
],
{ useNativeDriver: true }
)}
style={styles.scrollView}
contentContainerStyle={styles.endPadding}
>
{this.state.markers.map((marker, index) => (
<View style={styles.card} key={index}>
<Image
source={marker.image}
style={styles.cardImage}
resizeMode="cover"
/>
<View style={styles.textContent}>
<Text numberOfLines={1} style={styles.cardtitle}>{marker.title}</Text>
<Text numberOfLines={1} style={styles.cardDescription}>
{marker.description}
</Text>
</View>
</View>
))}
</Animated.ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
scrollView: {
position: "absolute",
bottom: 30,
left: 0,
right: 0,
paddingVertical: 10,
},
endPadding: {
paddingRight: width - CARD_WIDTH,
},
card: {
padding: 10,
elevation: 2,
backgroundColor: "#FFF",
marginHorizontal: 10,
shadowColor: "#000",
shadowRadius: 5,
shadowOpacity: 0.3,
shadowOffset: { x: 2, y: -2 },
height: CARD_HEIGHT,
width: CARD_WIDTH,
overflow: "hidden",
},
cardImage: {
flex: 3,
width: "100%",
height: "100%",
alignSelf: "center",
},
textContent: {
flex: 1,
},
cardtitle: {
fontSize: 12,
marginTop: 5,
fontWeight: "bold",
},
cardDescription: {
fontSize: 12,
color: "#444",
},
markerWrap: {
alignItems: "center",
justifyContent: "center",
},
marker: {
width: 8,
height: 8,
borderRadius: 4,
backgroundColor: "rgba(130,4,150, 0.9)",
},
ring: {
width: 24,
height: 24,
borderRadius: 12,
backgroundColor: "rgba(130,4,150, 0.3)",
position: "absolute",
borderWidth: 1,
borderColor: "rgba(130,4,150, 0.5)",
},
});
create a new file for tab navigation and add the following code:
(I imported your map component as screens)
import React from 'react';
import { Platform } from 'react-native';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import TabBarIcon from '../components/TabBarIcon';
import screens from '../screens/HomeScreen';
import SettingsScreen from '../screens/SettingsScreen';
const HomeStack = createStackNavigator({
Home: screens,
});
HomeStack.navigationOptions = {
tabBarLabel: 'Home',
tabBarIcon: ({ focused }) => (
<TabBarIcon
focused={focused}
name={
Platform.OS === 'ios'
? `ios-information-circle${focused ? '' : '-outline'}`
: 'md-information-circle'
}
/>
),
};
const SettingsStack = createStackNavigator({
Settings: SettingsScreen,
});
SettingsStack.navigationOptions = {
tabBarLabel: 'Settings',
tabBarIcon: ({ focused }) => (
<TabBarIcon
focused={focused}
name={Platform.OS === 'ios' ? 'ios-options' : 'md-options'}
/>
),
};
export default createBottomTabNavigator({
HomeStack,
SettingsStack,
});

react-native: image won't rerender when state changes

I have an icon as an image and I want to change the icon when a state property changes. Here is the relevant code:
<TouchableHighlight underlayColor="rgba(0,0,0,0)" style={styles.playButton} onPress={this._handleStartPress}>
<Image source={(this.state.started) ? require('./Control-pause.png') : require('./Control-play.png')} resizeMode="contain" style={styles.icon}/>
</TouchableHighlight>
The state changes correctly as expected (verifed by some console logs), but somehow the Image won't re render and change when this.state.started changes. The path to the images is also correct.
Any Ideas what's the problem?
EDIT: The whole component:
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
TouchableHighlight,
View,
ScrollView,
Vibration,
AlertIOS,
Image
} from 'react-native'
/*import Icon from 'react-native-vector-icons/FontAwesome';*/
const timer = require('react-native-timer');
const Button = require('./components/Button.js');
const PlayIcon = require('./Control-play.png');
const PauseIcon = require('./Control-pause.png');
class Project extends Component {
constructor(props) {
super(props);
this.state = {
timerValue: 25*60,
count: 0,
started: false,
};
this._tick = this._tick.bind(this);
this._runClock = this._runClock.bind(this);
this._stopClock = this._stopClock.bind(this);
this._handlePomodoroPress = this._handlePomodoroPress.bind(this);
this._handlePausePress = this._handlePausePress.bind(this);
this._getMinsSecs = this._getMinsSecs.bind(this);
this._finishedTimer = this._finishedTimer.bind(this);
this._handleStartPress = this._handleStartPress.bind(this);
}
_tick() {
if (this.state.timerValue > 0) {
this.setState({timerValue: this.state.timerValue - 1});
} else {
this._finishedTimer();
}
}
_finishedTimer() {
this.setState({started: false});
timer.clearInterval('timer');
Vibration.vibrate();
AlertIOS.alert("Time's up!");
}
_runClock() {
this.setState({started: true});
console.log("running: ", this.state.started);
timer.setInterval('timer', this._tick, 1000);
}
_stopClock() {
this.setState({started: false});
console.log("running: ", this.state.started);
timer.clearInterval('timer');
}
_getMinsSecs(seconds) {
let mins = Math.floor(seconds / 60);
let secs = seconds - mins * 60;
return (mins < 10 ? "0" : "") + mins + ":" + (secs <10 ? "0" : "") + secs;
}
_handleStartPress() {
if (!this.state.started) {
this._runClock();
} else {
this._stopClock();
}
}
_handlePomodoroPress() {
if (!this.state.started) {
this.setState({timerValue: 25*60});
}
}
_handlePausePress() {
if(!this.state.started) {
this.setState({ timerValue: 5*60 });
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.timeWrapper}>
<View style={styles.line}/>
<Text style={styles.time}>{this._getMinsSecs(this.state.timerValue)}</Text>
<View style={styles.line}/>
</View>
<TouchableHighlight underlayColor="rgba(0,0,0,0)" style={styles.playButton} onPress={this._handleStartPress}>
<Image source={(this.state.started) ? require('./Control-pause.png') : require('./Control-play.png')} resizeMode="contain" style={styles.icon}/>
</TouchableHighlight>
<View style={styles.buttonWrapper}>
<Button
value="Pomodoro"
onPress={this._handlePomodoroPress}/>
<Button value="Pause" onPress={this._handlePausePress}/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "space-around",
alignItems: 'center',
backgroundColor: "#7CCF9E"
},
time: {
fontSize: 74,
color: '#fff',
fontWeight: '200'
},
buttonWrapper: {
justifyContent: 'center',
alignItems: 'center'
},
playButton: {
width: 79,
height: 79,
borderRadius: 100,
borderWidth: 3,
borderColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
},
line: {
marginTop: 10,
height: 3,
width: 200,
backgroundColor: '#fff'
},
timeWrapper: {
alignItems: 'center'
},
icon: {
height: 42,
}
});
AppRegistry.registerComponent('Project', () => Project);
something like this works easily:
<TouchableHighlight underlayColor="rgba(0,0,0,0)" style={styles.playButton} onPress={this._handleStartPress}>
<Text>{this.state.started ? "started" : "stopped"}</Text>
</TouchableHighlight>
EDIT2:
I found what causes the picture not to rerender!!!!
When I style the size in the StyleSheet it won't rerender ... If it has no size style everything is fine!
require calls are not dynamic. They are statically analyzed and bundled. https://github.com/facebook/react-native/issues/2481 . As Andrew Axton suggested, load them in separate variables outside of render and using that in the conditional should work.

left side of screen untouchable when using NavigatorIOS react-native

I have this very strange bug on my react-native iOS app, when I'm using NavigatorIOS (need it) : there is a 30 points zone on the left of the screen that is not touchable on the first touch (nothing happens on touchableHighlight or TouchableWithoutFeedback) in Listview elements for example...
When I use Navigator, no problem at all, it's specific to NavigatorIOS (and I need it in this part of the app), also tried without any style, same problem.
Haven't seen any github issue or discussion about this bug.
Edit :
Runnable example : https://rnplay.org/apps/E0R2vg
Component code sample:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
NavigatorIOS,
ListView,
TouchableWithoutFeedback,
Dimensions,
} = React;
var myListView = React.createClass({
getInitialState: function() {
return {
ds: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
};
},
componentDidMount: function() {
console.log('feed datasource');
this.setState({
ds: this.state.ds.cloneWithRows([{name: 'one'}, {name:'two'}, {name: 'three'}]),
});
},
render: function() {
return (
<View style={styles.container}>
<ListView
dataSource={this.state.ds}
renderRow={this.renderItem}
style={styles.listView}
/>
<TouchableWithoutFeedback onPress={this.nextroute}>
<View style={[styles.pressme, {flex:1}]}>
<Text>Next route to see the issue</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
},
renderItem: function(item) {
return (
<View style={styles.row}>
<TouchableWithoutFeedback onPress={() => alert('pressed')}>
<View style={styles.pressme}>
<Text>x</Text>
</View>
</TouchableWithoutFeedback>
<Text>{item.name} - Item description...</Text>
</View>
);
},
nextroute: function() {
this.props.navigator.push({
title: 'Try press [x] (twice)',
component: myListView,
onLeftButtonPress: () => this.props.navigator.pop(),
});
},
});
var SampleApp = React.createClass({
render: function() {
return (
<NavigatorIOS
style={styles.navcontainer}
initialRoute={{
component: myListView,
title: 'First view is ok',
}}
tintColor="#000000"
barTintColor="#fd7672"
translucent={false}
ref='navios'
/>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 28,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
fontSize: 19,
marginBottom: 5,
},
navcontainer: {
flex: 1,
},
listView: {
flex: 1,
width: Dimensions.get('window').width,
},
row: {
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
backgroundColor: '#FFFFFF',
},
pressme: {
margin: 10,
borderWidth: 1,
borderColor: 'red',
padding: 15,
}
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);

Resources