How to connect to a device BLE? - android

I'm trying to do a connection to a device with BLE.
I need to connect to a specific device automatically.
I don't understand how I can do to connect directly to a device. Let me explain better, at the moment I can scan and I get all the bluetooth devices. Instead, I would like to directly connect to a specific device.
- I should therefore select only one type of device
- Connect me directly
What do you think I can do?
With this code i choose the name
return (
<View style={{borderBottomColor: 'lightgrey', borderBottomWidth: 1, alignItems: 'stretch'}}>
<View style={{flexDirection: 'row', alignItems: 'center', padding: 15}}>
<View style={{flex: 1}}>
<Text style={{fontSize: 20, color: '#888'}}>{`${peripheral.name}`}</Text>
</View>
<View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
<Btn onPress={() => onConnect(peripheral)}>
{`Connect`}
</Btn>
</View>
</View>
</View>
)
With this code I do the scan
return (
<View style={{flex: 1 , paddingTop: Theme.navbarHeight }}>
<StatusBar
/* backgroundColor={Theme.color}*/
/* barStyle="light-content" */
/>
{
Object.keys(peripherals).length === 0 ? (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
{ uiState === UiState.scanning && <ActivityIndicator size='large' color={Theme.color}/> }
<Text style={{marginBottom: 10, fontSize: 18, color: '#999'}}>
Nessun Risultato
</Text>
{ uiState === UiState.idle && <Btn onPress={this._doScan}>Scansione</Btn> }
</View>
) : (
<ScrollView style={{ flex: 1 }} contentContainerStyle={{ alignItems: 'stretch' }}>
{
Object.keys(peripherals).map(key => peripherals[key]).map(
peripheral => (
<Peripheral
key={peripheral.id}
peripheral={peripheral}
onConnect={onConnect}
/>
)
)
}
</ScrollView>
)
}
</View>
)
}
_renderScanButton = () => {
let {uiState} = this.state;
if (uiState === UiState.scanning) {
return <ActivityIndicator color='white'/>
}
return (
<TouchableOpacity onPress={this._doScan}>
<Text style={{color: 'white', width: 100, textAlign: 'right'}}>Scansione</Text>
</TouchableOpacity>
)
}
_doScan = () => {
if (this.state.uiState !== UiState.idle) {
return;
}
this.setState({ uiState: UiState.scanning, peripherals: {} });
BleManager.scan([], 5, true)
.then(results => {
console.log('Scansione in corso...');
})
.catch(() => {
this.setState({ uiState: UiState.idle })
})
}
}

You are using react-native-ble-manager. According to their docs, you can connect to a peripheral using the connect method:
BleManager.connect('XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX')
.then(() => {
// Success code
console.log('Connected');
})
.catch((error) => {
// Failure code
console.log(error);
});
You should get the peripheral UID from the scan method results:
BleManager.scan([], 5, true)
.then(results => {
// Success code
console.log(results);
});
I personally do not use the react-native-ble-manager package but the react-native-ble-plx package, but the process is pretty similar. Here's how I do it:
manager.startDeviceScan(null, null, async (error, device) => {
console.log("scanning bluetooth...")
if (device.name === "MY_DEVICE_NAME") {
manager
.connectToDevice(device.id, {
autoconnect: true,
timeout: BLUETOOTH_TIMEOUT
})
// ............
}
})

Related

Error when implementing stripe payment with react native expo

I am facing an error trying to implement Stripe payment with react native and Expo SDK.
The scenario is very simple where I add items to the cart and then choose payment option as card to pay, but when I click on Card an error shows up. the error and code are below.
import { StatusBar } from "expo-status-bar";
import React from "react";
import {
StyleSheet,
Text,
View,
Button,
Pressable,
Platform,
} from "react-native";
import { StripeProvider } from "#stripe/stripe-react-native";
import { initStripe, useStripe } from "#stripe/stripe-react-native";
import GooglePayMark from "./GooglePayMark";
import ApplePayMark from "./ApplePayMark";
const API_URL = "http://192.168.0.163:3000";
const ProductRow = ({ product, cart, setCart }) => {
const modifyCart = (delta) => {
setCart({ ...cart, [product.id]: cart[product.id] + delta });
};
return (
<View style={styles.productRow}>
<View style={{ flexDirection: "row" }}>
<Text style={{ fontSize: 17, flexGrow: 1 }}>
{product.name} - {product.price}$
</Text>
<Text style={{ fontSize: 17, fontWeight: "700" }}>
{cart[product.id]}
</Text>
</View>
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
marginTop: 8,
}}
>
<Button
disabled={cart[product.id] <= 0}
title="Remove"
onPress={() => modifyCart(-1)}
/>
<Button title="Add" onPress={() => modifyCart(1)} />
</View>
</View>
);
};
const ProductsScreen = ({ products, navigateToCheckout }) => {
/**
* We will save the state of the cart here
* It will have the inital shape:
* {
* [product.id]: 0
* }
*/
const [cart, setCart] = React.useState(
Object.fromEntries(products.map((p) => [p.id, 0]))
);
const handleContinuePress = async () => {
/* Send the cart to the server */
const URL = `${API_URL}/create-payment-intent`;
const response = await fetch(URL, {
method: "POST",
headers: {
"Content-Type": "application-json",
},
body: JSON.stringify(cart),
});
/* Await the response */
const { publishableKey, clientSecret, merchantName } =
await response.json();
/* Navigate to the CheckoutScreen */
/* You can use navigation.navigate from react-navigation */
navigateToCheckout({
publishableKey,
clientSecret,
merchantName,
cart,
products,
});
};
return (
<View style={styles.screen}>
{products.map((p) => {
return (
<ProductRow key={p.id} product={p} cart={cart} setCart={setCart} />
);
})}
<View style={{ marginTop: 16 }}>
<Button title="Continue" onPress={handleContinuePress} />
</View>
</View>
);
};
/**
* CheckoutScreen related components
*/
const CartInfo = ({ products, cart }) => {
return (
<View>
{Object.keys(cart).map((productId) => {
const product = products.filter((p) => p.id === productId)[0];
const quantity = cart[productId];
return (
<View
key={productId}
style={[{ flexDirection: "row" }, styles.productRow]}
>
<Text style={{ flexGrow: 1, fontSize: 17 }}>
{quantity} x {product.name}
</Text>
<Text style={{ fontWeight: "700", fontSize: 17 }}>
{quantity * product.price}$
</Text>
</View>
);
})}
</View>
);
};
const MethodSelector = ({ onPress, paymentMethod }) => {
// ...
return (
<View style={{ marginVertical: 48, width: "75%" }}>
<Text
style={{
fontSize: 14,
letterSpacing: 1.5,
color: "black",
textTransform: "uppercase",
}}
>
Select payment method
</Text>
{/* If there's no paymentMethod selected, show the options */}
{!paymentMethod && (
<Pressable
onPress={onPress}
style={{
flexDirection: "row",
paddingVertical: 8,
alignItems: "center",
}}
>
{Platform.select({
ios: <ApplePayMark height={59} />,
android: <GooglePayMark height={59} />,
})}
<View style={[styles.selectButton, { marginLeft: 16 }]}>
<Text style={[styles.boldText, { color: "#007DFF" }]}>Card</Text>
</View>
</Pressable>
)}
{/* If there's a paymentMethod selected, show it */}
{!!paymentMethod && (
<Pressable
onPress={onPress}
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingVertical: 8,
}}
>
{paymentMethod.label.toLowerCase().includes("apple") && (
<ApplePayMark height={59} />
)}
{paymentMethod.label.toLowerCase().includes("google") && (
<GooglePayMark height={59} />
)}
{!paymentMethod.label.toLowerCase().includes("google") &&
!paymentMethod.label.toLowerCase().includes("apple") && (
<View style={[styles.selectButton, { marginRight: 16 }]}>
<Text style={[styles.boldText, { color: "#007DFF" }]}>
{paymentMethod.label}
</Text>
</View>
)}
<Text style={[styles.boldText, { color: "#007DFF", flex: 1 }]}>
Change payment method
</Text>
</Pressable>
)}
</View>
);
};
const CheckoutScreen = ({
products,
navigateBack,
publishableKey,
clientSecret,
merchantName,
cart,
}) => {
// We will store the selected paymentMethod
const [paymentMethod, setPaymentMethod] = React.useState();
// Import some stripe functions
const { initPaymentSheet, presentPaymentSheet, confirmPaymentSheetPayment } =
useStripe();
// Initialize stripe values upon mounting the screen
React.useEffect(() => {
(async () => {
await initStripe({
publishableKey,
// Only if implementing applePay
// Set the merchantIdentifier to the same
// value in the StripeProvider and
// striple plugin in app.json
merchantIdentifier: "yourMerchantIdentifier",
});
// Initialize the PaymentSheet with the paymentIntent data,
// we will later present and confirm this
await initializePaymentSheet();
})();
}, []);
const initializePaymentSheet = async () => {
const { error, paymentOption } = await initPaymentSheet({
paymentIntentClientSecret: clientSecret,
customFlow: true,
merchantDisplayName: merchantName,
style: "alwaysDark", // If darkMode
googlePay: true, // If implementing googlePay
applePay: true, // If implementing applePay
merchantCountryCode: "ES", // Countrycode of the merchant
testEnv: __DEV__, // Set this flag if it's a test environment
});
if (error) {
console.log(error);
} else {
// Upon initializing if there's a paymentOption
// of choice it will be filled by default
setPaymentMethod(paymentOption);
}
};
const handleSelectMethod = async () => {
const { error, paymentOption } = await presentPaymentSheet({
confirmPayment: false,
});
if (error) {
alert(`Error code: ${error.code}`, error.message);
}
setPaymentMethod(paymentOption);
};
const handleBuyPress = async () => {
if (paymentMethod) {
const response = await confirmPaymentSheetPayment();
if (response.error) {
alert(`Error ${response.error.code}`);
console.error(response.error.message);
} else {
alert("Purchase completed!");
}
}
};
return (
<View style={styles.screen}>
<CartInfo cart={cart} products={products} />
<MethodSelector
onPress={handleSelectMethod}
paymentMethod={paymentMethod}
/>
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
alignSelf: "stretch",
marginHorizontal: 24,
}}
>
<Pressable onPress={navigateBack}>
<Text style={[styles.textButton, styles.boldText]}>Back</Text>
</Pressable>
<Pressable style={styles.buyButton} onPress={handleBuyPress}>
<Text style={[styles.boldText, { color: "white" }]}>Buy</Text>
</Pressable>
</View>
</View>
);
};
const AppContent = () => {
const products = [
{
price: 10,
name: "Pizza Pepperoni",
id: "pizza-pepperoni",
},
{
price: 12,
name: "Pizza 4 Fromaggi",
id: "pizza-fromaggi",
},
{
price: 8,
name: "Pizza BBQ",
id: "pizza-bbq",
},
];
const [screenProps, setScreenProps] = React.useState(null);
const navigateToCheckout = (screenProps) => {
setScreenProps(screenProps);
};
const navigateBack = () => {
setScreenProps(null);
};
return (
<View style={styles.container}>
{!screenProps && (
<ProductsScreen
products={products}
navigateToCheckout={navigateToCheckout}
/>
)}
{!!screenProps && (
<CheckoutScreen {...screenProps} navigateBack={navigateBack} />
)}
</View>
);
};
export default function App() {
return (
<StripeProvider>
<AppContent />
</StripeProvider>
);
}
so having this code I was able to get the application running and the items were added to the cart but when I click on card option the error shows up.
I believe the error is generated at the CheckoutScreen.
error showing
Looks like this is what happened:
Your code invoked presentPaymentSheet.
It internally invoked flowController?.presentPaymentOptions.
It checked and found FlowController wasn't properly initialized and emit that
error.
The reason FlowController is not properly initialized is because there was null or empty client secret passed in. You would want to check if your clientSecret variable from navigateToCheckout actually had a value.

React Native: Firebase OTP issues in android device

I have implemented the functionality of firebase OTP, for authentication of the user to my App.
When I created the build, The OTP functionality is working fine with IOS but not with android, in android the OTP expires soon.
Here is the case:
Case 1
Android Device A
App installed in device A, and register with the mobile number of Device A (the same device),
I got the OTP but when I entered it shows me an invalid OTP due to the OTP had been expired already
Case 2
Android Device A, and Android Device B
App installed in device A, and registered with the mobile number of Device B,
I got the OTP on Device B and I entered it in device A where the app is installed, It was working fine.
Here is my code and configuration
import React, { Fragment, Component } from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
TextInput,
Button,
Animated,
} from 'react-native';
import auth from '#react-native-firebase/auth';
import { COLORS } from './App/Auth/Colors';
import { STRINGS } from './App/Resource/Strings';
import { Animation_Open, Animation_Close } from './App/Auth/Functions';
export default class Demo extends Component {
constructor(props) {
super(props);
this.animatedValue = new Animated.Value(-500);
this.state = {
phone: '+91',
code: '',
confirm: null,
};
}
componentDidMount() {
console.log('componentDidMount Demo');
}
OnPressContinue = async () => {
auth()
.signInWithPhoneNumber(this.state.phone)
.then(confirmResult => {
console.log('confirmResult', confirmResult);
this.setState({ confirm: confirmResult });
})
.catch(error => {
console.log('My Error', error);
});
}
OnPressCodeSent = async () => {
try {
var a = await this.state.confirm.confirm(this.state.code);
console.log('a', a);
} catch (error) {
console.log('Invalid code.', error);
}
}
render() {
return (
<SafeAreaView style={styles.container}>
<StatusBar />
<View>
<View>
<TextInput
placeholder="Enter A Number"
value={this.state.phone}
onChangeText={(text) => this.setState({ phone: text })}
keyboardType="numeric"
style={{ padding: 10, borderBottomWidth: 1, width: '100%', color: 'black' }}
/>
<View style={{ marginTop: 20 }}>
<Button
title="Continue"
onPress={() => this.OnPressContinue()} />
</View>
</View>
<View style={{ marginTop: 20 }}>
<TextInput
placeholder="Enter Code"
value={this.state.code}
onChangeText={(text) => this.setState({ code: text })}
style={{ padding: 10, borderBottomWidth: 1, width: '100%', color: 'black' }}
/>
<View style={{ marginTop: 20 }}>
<Button
title="Send"
onPress={() => this.OnPressCodeSent()} />
</View>
</View>
</View>
{/* //! Toster */}
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
The issue has been resolved:
If the OTP will receive in the same device we will auto add, and compare.

react-native-camera (android): takePictureAsync() throws error

After calling takePictureAsync() from react-native-camera, i'm getting this error:
{
"framesToPop": 1,
"nativeStackAndroid": [],
"userInfo": null,
"message": "Preview is paused - resume it before taking a picture.",
"code": "E_TAKE_PICTURE_FAILED",
"line": 2131,
"column": 45,
"sourceURL": "http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false"
}
So I tried using resumePreview() method before calling takePictureAsync() and now I'm getting a different error message:
{
"framesToPop": 1,
"nativeStackAndroid": [],
"userInfo": null,
"message": "takePicture failed",
"code": "E_TAKE_PICTURE_FAILED",
"line": 2131,
"column": 45,
"sourceURL": "http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false"
}
My component and usage i identical to that of https://react-native-community.github.io/react-native-camera/docs/rncamera
<RNCamera
ref={ref => {
this.camera = ref;
}}
style={styles.preview}
type={RNCamera.Constants.Type.back}
flashMode={RNCamera.Constants.FlashMode.on}
androidCameraPermissionOptions={{
title: 'Permission to use camera',
message: 'We need your permission to use your camera',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
androidRecordAudioPermissionOptions={{
title: 'Permission to use audio recording',
message: 'We need your permission to use your audio',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
onGoogleVisionBarcodesDetected={({ barcodes }) => {
console.log(barcodes);
}}
/>
takePicture = async () => {
if (this.camera) {
const options = { quality: 0.5, base64: true };
try {
this.camera.resumePreview();
const data = await this.camera.takePictureAsync(options);
console.log(data.uri);
} catch (error) {
console.log(JSON.stringify(error, null, 2));
}
}
};
versions:
"react-native": "0.61.2",
"react-native-camera": "git+https://git#github.com/react-native-community/react-native-camera.git",
Works fine on iOS.
Is this an issue with the library or my implementation?
Try to use component as FaCC (Function as Child Components)! This way worked for me.
const PendingView = () => (
<View
style={{
flex: 1,
backgroundColor: 'lightgreen',
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text>Waiting</Text>
</View>
);
class ExampleApp extends PureComponent {
render() {
return (
<View style={styles.container}>
<RNCamera
style={styles.preview}
type={RNCamera.Constants.Type.back}
>
{({ camera, status, recordAudioPermissionStatus }) => {
if (status !== 'READY') return <PendingView />;
return (
<View style={{ flex: 0, flexDirection: 'row', justifyContent: 'center' }}>
<TouchableOpacity onPress={() => this.takePicture(camera)} style={styles.capture}>
<Text style={{ fontSize: 14 }}> SNAP </Text>
</TouchableOpacity>
</View>
);
}}
</RNCamera>
</View>
);
}
takePicture = async function(camera) {
const options = { quality: 0.5, base64: true };
const data = await camera.takePictureAsync(options);
// eslint-disable-next-line
console.log(data.uri);
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'black',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
padding: 15,
paddingHorizontal: 20,
alignSelf: 'center',
margin: 20,
},
});
Is this an issue with the library or my implementation?
It appears to be a problem with the example code. I noticed the same thing and my solution is similar to FredVieira but doesn't use FaCC. It appears that the camera will not resume on Android unless the RNCamera component has children. So if you change the example from
<RNCamera ... />
<View ...>
<TouchableOpacity ...>
<Text style={{ fontSize: 14 }}> SNAP </Text>
</TouchableOpacity>
</View>
to
<RNCamera ...>
<View ...>
<TouchableOpacity ...>
<Text style={{ fontSize: 14 }}> SNAP </Text>
</TouchableOpacity>
</View>
</RNCamera>
it should work. So you can use a function or a component, just as long as the RNCamera has a child.

how to render new elements at the end of current screen - REACT NATIVE

I'm working on a news app, and this is the news details screens, it renders all the news details but i want to render the next news below this one when the end is reached. I can manage to get the new news details by using isCloseToBottom method and i can render the new news but the old one get replaced, but i don't want the old news to disappear. Is there any workaround for this?
class NewsDetails extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: false,
loaded: false,
article: {},
request_control:1
};
}
componentWillMount() {
const { params } = this.props.navigation.state;
console.log(params.id);
axios
.get(`${URL_NEWS_DETAILS}/${params.id}`)
.then(response =>
this.setState({
article: response.data,
loaded: true,
})
)
.catch(error => console.log(error));
}
_onRefresh=()=>{
this.setState({refreshing: true})
axios.get(`${URL_NEWS_DETAILS}/210971`) //test with constant id
.then(response =>
this.setState({
article: response.data,
loaded: true,
})
)
.catch(error => console.log(error));
this.setState({refreshing: false});
};
renderNext=()=>{
if(this.state.request_control===1) {
this.setState({request_control: 0});
axios.get(`${URL_NEWS_DETAILS}/210971`) //test with constant id
.then(response => {
this.setState({
request_control:1,
article: response.data,
loaded: true
})
},
)
.catch(error => {
this.setState({ loaded: true})
console.log(error)
})
}
};
render() {
if (this.state.loaded) {
return (
<View style={styles.container}>
<ScrollView showsVerticalScrollIndicator={false}
onScroll={({nativeEvent}) => {
if (isCloseToBottom(nativeEvent)) {
this.renderNext()
}
}}
scrollEventThrottle={400}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._onRefresh.bind(this)}
/>
}>
<Text style={styles.title}>
{this.state.article.title.rendered.replace("–", "-")}
</Text>
<View
style={{ marginTop: 10, marginBottom: 10, flexDirection: 'row', alignItems: 'center' }}>
<Image
style={{ width: 18, height: 18 }}
source={require('../../img/icon.png')}
/>
<Text style={{ fontFamily: 'Open Sans Bold', fontSize: 14 }}>
{' '}
{this.state.article.author}
</Text>
<Text style={{ fontFamily: 'Open Sans Regular', fontSize: 13 }}>
{' '}
në{' '}
</Text>
{this.state.article.categories.map(category => {
return (
<Text
style={{
fontFamily: 'Open Sans Regular',
fontSize: 13,
color: '#F33A22',
}}>
{category.name},{' '}
</Text>
);
})}
</View>
<Lightbox underlayColor="white">
<Image
style={styles.image}
source={{ uri: this.state.article.featured_image_url }}
/>
</Lightbox>
<HTMLView
value={'<div>' + this.state.article.content.raw + '</div>'}
renderNode={Platform.OS === 'android' ? this.renderNode : null}
stylesheet={htmlStyles}
/>
{/*HERE I NEED TO RENDER A NEW NEWS BELOW THE MAIN ONE, */}
{/*TO CREATE AN EFFECT LIKE USED IN WEB THAT DISPLAYS NEWS AFTER NEWS*/}
</ScrollView>
</View>
);
} else return <Spinner />;
}
}
Your state article is replaced by the new one when you call renderNext, so the old one get replaced. To fix that, just change like
renderNext=()=>{
if(this.state.request_control===1) {
this.setState({request_control: 0});
axios.get(`${URL_NEWS_DETAILS}/210971`) //test with constant id
.then(response => {
this.setState({
request_control:1,
article: [...this.state.article, ...response.data],
loaded: true
})
},
)
.catch(error => {
this.setState({ loaded: true})
console.log(error)
})
}
};

How to start another component in react native

I am learning react-native programming where I have one component in index.android.js. I have a TouchableOpacity in that component. I want to start next component on click on TouchableOpacity.
<TouchableOpacity style={{ height: 40, marginTop: 10 , backgroundColor: '#2E8B57'}} onPress={}>
<Text style={{color: 'white', textAlign: 'center', marginTop: 10, fontWeight: 'bold'}}>LOGIN</Text>
</TouchableOpacity>
Can anyone suggest that How can I set click listener in onPress and how to start next component on clicking on this.
Thanks in advance.
Try like this
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
} = React;
var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop, {
snapVelocity: 8,
});
var CustomSceneConfig = Object.assign({}, BaseConfig, {
springTension: 100,
springFriction: 1,
gestures: {
pop: CustomLeftToRightGesture,
}
});
var PageOne = React.createClass({
_handlePress() {
this.props.navigator.push({id: 2,});
},
render() {
return (
<View style={[styles.container, {backgroundColor: 'green'}]}>
<Text style={styles.welcome}>Greetings!</Text>
<TouchableOpacity onPress={this._handlePress}>
<View style={{paddingVertical: 10, paddingHorizontal: 20, backgroundColor: 'black'}}>
<Text style={styles.welcome}>Go to page two</Text>
</View>
</TouchableOpacity>
</View>
)
},
});
var PageTwo = React.createClass({
_handlePress() {
this.props.navigator.pop();
},
render() {
return (
<View style={[styles.container, {backgroundColor: 'purple'}]}>
<Text style={styles.welcome}>This is page two!</Text>
<TouchableOpacity onPress={this._handlePress}>
<View style={{paddingVertical: 10, paddingHorizontal: 20, backgroundColor: 'black'}}>
<Text style={styles.welcome}>Go back</Text>
</View>
</TouchableOpacity>
</View>
)
},
});
var SampleApp = React.createClass({
_renderScene(route, navigator) {
if (route.id === 1) {
return <PageOne navigator={navigator} />
} else if (route.id === 2) {
return <PageTwo navigator={navigator} />
}
},
_configureScene(route) {
return CustomSceneConfig;
},
render() {
return (
<Navigator
initialRoute={{id: 1, }}
renderScene={this._renderScene}
configureScene={this._configureScene} />
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: 'white',
},
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
module.exports = SampleApp;
refer this link
The entire point of touchable opacity is to touch it.
Put your Business Logic in a seperate class and call it from the Touchable opacity event. Then use that logic in your code where ever you want!
You can do conditional rendering in a single component depending on state/props, so maybe something like this:
render() {
return state.displayComponent?
<NewComponent /> :
<TouchableOpacity ... onPress={() => this.setState({displayComponent: true})} />
}
, but if you're looking for something more robust, read up on react-native-router-flux

Categories

Resources