React Native Navigation with React Native Admob About - reactjs

I created a 3 page application with React native navigation. Admob ads are on the 3rd page. I want to try the same ad code on all three screens. If there is any idea in this matter, please share. Thank you.
For better understanding I give the following expo code.
import React, { Component } from 'react';
import {
WebView,
AppRegistry,
StyleSheet,
Text,
View,
Button,
Alert
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import ListComponent from './ListComponent';
class App extends Component {
static navigationOptions = {
title: 'App',
};
OpenSecondActivityFunction = () => {
this.props.navigation.navigate('Second');
};
render() {
return (
<View style={styles.container}>
<Button
onPress={this.OpenSecondActivityFunction}
title="Open Second Activity"
/>
</View>
);
}
}
class SecondActivity extends Component {
static navigationOptions = {
title: 'SecondActivity',
};
OpenThirdActivityFunction = data => {
this.props.navigation.navigate('Third');
};
render() {
return (
<View style={{ flex: 1 }}>
<ListComponent
OpenThirdActivityFunction={this.OpenThirdActivityFunction}
/>
</View>
);
}
}
class ThirdActivity extends Component {
static navigationOptions = {
title: 'ThirdSecondActivity',
};
render() {
return (
<View style={{ flex: 1 }}>
<Text>3</Text>
</View>
);
}
}
const ActivityProject = StackNavigator({
First: { screen: App },
Second: { screen: SecondActivity },
Third: { screen: ThirdActivity },
});
export default ActivityProject;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
Listcomponent.js
import React, { Component } from 'react';
import {
AppRegistry,
View,
Text,
FlatList,
ActivityIndicator,
} from 'react-native';
import { List, ListItem, SearchBar } from 'react-native-elements';
class ListComponents extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
page: 1,
seed: 1,
error: null,
refreshing: false,
};
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: '98%',
backgroundColor: '#CED0CE',
marginLeft: '2%',
}}
/>
);
};
renderHeader = () => {
return <SearchBar placeholder="Type Here..." lightTheme round />;
};
renderFooter = () => {
if (!this.state.loading) return null;
return (
<View
style={{
paddingVertical: 20,
borderTopWidth: 1,
borderColor: '#CED0CE',
}}>
<ActivityIndicator animating size="large" />
</View>
);
};
render() {
return (
<List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
<FlatList
data={[{ name: 1, coders: 2 }]}
renderItem={({ item }) => (
<ListItem
roundAvatar
title={`${item.name}`}
subtitle={item.coders}
containerStyle={{ borderBottomWidth: 0 }}
onPress={() => this.props.OpenThirdActivityFunction(item.coders)}
/>
)}
keyExtractor={item => item.coders}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
ListFooterComponent={this.renderFooter}
/>
</List>
);
}
}
export default ListComponents;

Related

Switch navigator does not works in React Native

I've asked a question already, and modified as much as I can, but still in trouble.
Combined all children Screen js files into App.js
When I compile and run, App shows LoginScreen.js, not LoadingScreen.js.
Also, onPress={this.props.navigation.navigate('Loading')} does not works. If I press the button, it shows nothing.
What am I still missing?
import React from 'react'
import { StyleSheet, Platform, Image, Text, View, TextInput, Button, ActivityIndicator } from 'react-native'
import { createAppContainer, createSwitchNavigator } from 'react-navigation'
import { createBottomTabNavigator } from 'react-navigation-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';
class LoadingScreen extends React.Component {
render() {
return (
<View style={styles.loadingcontainer}>
<Text>Loading</Text>
<ActivityIndicator size="large" />
<Button title="Move to LoginScreen" onPress={this.props.navigation.navigate('Login')} />
</View>
)
}
}
class LoginScreen extends React.Component {
state = { email: '', password: '' }
render() {
return (
<View style={styles.logincontainer}>
<Button
title='Sign in' onPress={this.props.navigation.navigate('Loading')}
/>
<Button
title='Sign Up'
/>
</View>
)
}
}
const styles = StyleSheet.create({
loadingcontainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
logincontainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
logintextInput: {
height: 40,
width: '90%',
borderColor: 'gray',
borderWidth: 1,
marginTop: 8
},
})
const App = createSwitchNavigator(
{
Loading: {
screen: LoadingScreen,
},
Login: {
screen: LoginScreen,
},
}
);
export default createAppContainer(App);
Thank you for your help.
For just navigation, you can use a stack navigator. The switch navigator used for conditional rendering of two different stacks. Anyways you can set loading as the first screen buy setting initialRouteName to loading. Here is an example
createSwitchNavigator(
{
LimitedAccess: {
screen: Trial,
},
AppScreens: {
screen: AppScreens,
},
AuthScreens: {
screen: AuthScreens,
},
},
{
initialRouteName: signedIn ? 'AppScreens' : 'AuthScreens',
},
),
);
Note: Here signedIn is a conditional operator which decides the rendering of stacks.
The way your props are currently defined causes them to be instantly executed.
The onPress prop is instantly executed.
return (
<View style={styles.loadingcontainer}>
<Text>Loading</Text>
<ActivityIndicator size="large" />
<Button title="Move to LoginScreen" onPress={this.props.navigation.navigate('Login')} />
</View>
)
You should instead attach a function to onPress that can be executed when the button is pressed.
return (
<View style={styles.loadingcontainer}>
<Text>Loading</Text>
<ActivityIndicator size="large" />
<Button title="Move to LoginScreen" onPress={() => this.props.navigation.navigate('Login')} />
</View>
)
Your onPress-calls are running instantly, which causes your problems.
Change to:
import React from 'react'
import { StyleSheet, Platform, Image, Text, View, TextInput, Button, ActivityIndicator } from 'react-native'
import { createAppContainer, createSwitchNavigator } from 'react-navigation'
import { createBottomTabNavigator } from 'react-navigation-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';
class LoadingScreen extends React.Component {
render() {
return (
<View style={styles.loadingcontainer}>
<Text>Loading</Text>
<ActivityIndicator size="large" />
<Button title="Move to LoginScreen" onPress={() => this.props.navigation.navigate('Login')} />
</View>
)
}
}
class LoginScreen extends React.Component {
state = { email: '', password: '' }
render() {
return (
<View style={styles.logincontainer}>
<Button
title='Sign in' onPress={() => this.props.navigation.navigate('Loading')}
/>
<Button
title='Sign Up'
/>
</View>
)
}
}
const styles = StyleSheet.create({
loadingcontainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
logincontainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
logintextInput: {
height: 40,
width: '90%',
borderColor: 'gray',
borderWidth: 1,
marginTop: 8
},
})
const App = createSwitchNavigator(
{
Loading: {
screen: LoadingScreen,
},
Login: {
screen: LoginScreen,
},
}
);
export default createAppContainer(App);

How to set the state from a button inside static navigationoption react-native?

I want to click the TouchableOpacity and set the state true so that will open. I am getting error. and how to align the button in center at the header? alignSelf is not working.
`
import React, {Component} from 'react';
import {
StyleSheet,
SafeAreaView,
View,
TouchableOpacity,
Text,
} from 'react-native';
import Menu from '../../src/components/menubar';
export default class SearchPage extends Component {
constructor(props) {
super(props);
this.state = {isMenubarDisplayed: false};
}
static navigationOptions = {
headerTitle: () => {
return (
<TouchableOpacity
onPress={()=> this.setState({isMenubarDisplayed: true})}>
<Icon name="search" size={20} color="#000" />
</TouchableOpacity>
);
},
headerTitleStyle: {
alignSelf: 'center',
flex: 1,
},
};
render() {
return (
<SafeAreaView style={styles.container}>
{this.state.isMenubarDisplayed ? (
<Menu />
) : null}
</SafeAreaView>
);
}
}`
You need to try this, expo-snack .
This is my below code for search.js ,
import * as React from 'react';
import { Text, View, StyleSheet,TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
import Menu from './menu';
import Icon from 'react-native-vector-icons/FontAwesome';
export default class Search extends React.Component {
constructor(props){
super(props);
this.state={
isMenubarDisplayed: false,
}
}
static navigationOptions = ({ navigation }) => {
return {
headerTitle: () => {
return (
<TouchableOpacity onPress={navigation.getParam('toggleMenu')}>
<Icon name="search" size={20} color="#000" />
</TouchableOpacity>
);
},
};
};
toggleMenu = () => {
this.setState({ isMenubarDisplayed: !this.state.isMenubarDisplayed})
}
renderMenu = () => (
<Menu />
)
componentDidMount(){
this.props.navigation.setParams({
toggleMenu: this.toggleMenu
});
}
render() {
return (
<View style={styles.container}>
{this.state.isMenubarDisplayed?this.renderMenu():<View></View>}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
});
Hope it helps. feel free for doubts.
This is all you need https://reactnavigation.org/docs/en/header-buttons.html#header-interaction-with-its-screen-component
static navigationOptions = ({ navigation }) => {
return {
headerTitle: () => {
return (
<View style={{ flex: 1, alignItems: 'center' }}>
<TouchableOpacity onPress={navigation.getParam('toggleMenu')}>
<Icon name="search" size={20} color="#000" />
</TouchableOpacity>
</View>
);
},
};
};
componentDidMount() {
this.props.navigation.setParams({ toggleMenu: this.toggleMenu });
}
toggleMenu = () => {
this.setState({isMenubarDisplayed: true});
}

Expo Camera only opening once with React Navigation

I set the Expo camera to open on the middle tab with react navigation. However, the camera only opens when I click on that tab the first time. If I switch off of it and go back it's just a black screen. Also the take a picture button is not there. (I am new with react native and kinda coding as a whole)
'use strict';
import React, { Component } from 'react';
import { createBottomTabNavigator } from 'react-navigation';
import { Camera, Permissions } from 'expo';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
TouchableOpacity,
View,
Button
} from 'react-native';
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home!</Text>
</View>
);
}
}
class CameraView extends React.Component {
state = {
hasCameraPermission: null,
type: Camera.Constants.Type.back,
};
async componentWillMount() {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status === 'granted' });
}
render() {
const { hasCameraPermission } = this.state;
if (hasCameraPermission === null) {
return <View />;
} else if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }} type={this.state.type}>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
}}>
<TouchableOpacity
style={{
flex: 0.1,
alignSelf: 'flex-end',
alignItems: 'center',
}}
onPress={() => {
this.setState({
type: this.state.type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back,
});
}}>
<Text
style={{ fontSize: 18, marginBottom: 10, color: 'white' }}>
{' '}Flip{' '}
</Text>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
}
}
class SettingsScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Settings!</Text>
</View>
);
}
}
export default createBottomTabNavigator({
Home: HomeScreen,
Camera:CameraView,
Settings: SettingsScreen
});
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
top: 250
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
padding: 15,
paddingHorizontal: 20,
alignSelf: 'center',
margin: 20
}
});
With react navigation 5.x
import { useIsFocused } from '#react-navigation/native';
export const CameraView = (props) => {
const isFocused = useIsFocused();
return (
<View>
{ isFocused && <RNCamera /> }
</View>
)
}
useIsFocused Documentation
I had some issue.
This code solved it:
import { useIsFocused } from '#react-navigation/native';
function MyComponent() {
const isFocused = useIsFocused()
return (
<View>
{ isFocused && <RNCamera /> }
</View>
)
}
Old navigation
import { withNavigationFocus } from 'react-navigation'
render() {
const { isFocused } = this.props
return (
<View>
{ isFocused && <RNCamera ... /> }
</View>
)
}
export default withNavigationFocus(Camera)
To make this work you need to:
1.
import { NavigationEvents } from 'react-navigation';
state = { loaded: true }
render() {
const { loaded } = this.state;
return (
<View style={styles.container}>
<NavigationEvents
onWillFocus={payload => this.setState({loaded: true})}
onDidBlur={payload => this.setState({loaded: false})}/>
<View style={styles.cameraArea}>
{loaded && (
<Camera
type={Camera.Constants.Type.back}
ref={ref => {
this.camera = ref;
}}
/>
)}
</View>
The idea is to hide this camera view (onDidBlur-> loaded: false), then when you come back (onWillFocus is triggered and change loaded to true). When render() function is called it will show the <Camera /> again.
If you have any questions, feel free to ask.
This works for me. ( Navigation 5.x )
if you are using a different screen for CAMERA, you can easy unmount the screen when moving to another.
Reason of this behavior : Only one Camera preview can be active at any
given time. If you have multiple screens in your app, you should
unmount Camera components whenever a screen is unfocused.
<Stack.Screen name="camera" component={CameraScreen} options={{unmountOnBlur: true}}/>
</Stack.Navigator>
Documentation Link : https://docs.expo.io/versions/latest/sdk/camera/
Thanks.
I got it working by using NavigationEvents to determine if the tab is in focus and from there mount and unmount the camera. This also frees up the camera, if you need to use it in another screen. Here is what I would do in your example:
import { NavigationEvents } from 'react-navigation';
...
class CameraView extends React.Component {
constructor(props) {
super(props)
this.state = {
hasCameraPermission: null,
type: Camera.Constants.Type.back,
isFocused:true
};
}
...
render(){
//...your existing if's
} if(this.state.isFocused === false){
return (
<NavigationEvents
onWillFocus={payload => {
//console.log("will focus", payload);
this.setState({isFocused:true})
}}
onDidBlur={payload => {
//console.log('did leave',payload)
this.setState({isFocused:false})
}}
/>
)
}
} else {
return (
<View style={{ flex: 1 }}>
<Camera style={{ flex: 1 }} type={this.state.type}>
<NavigationEvents
onWillFocus={payload => {
//console.log("will focus", payload);
this.setState({isFocused:true})
}}
onDidBlur={payload => {
//console.log('did leave',payload)
this.setState({isFocused:false})
}}
/>
//...the rest of your camera code
}
I hope it works for you as well
I solved it using the hook useIsFocused from react-navigation/native. I tested it on Android, iOS and Web
import { useIsFocused } from '#react-navigation/native';
...
const isFocused = useIsFocused();
...
return (
isFocused && (
<Camera
ref={(ref) => {
camera = ref;
}}
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
)
);
If you are using RN Expo with React Navigation - Tab Navigator.
Then just use unmountOnBlur - unmountOnBlur Documentation
This will force the camera to unmount on every navigation focus changes.
in Expo react native
import { useIsFocused } from '#react-navigation/native';
const isFocused = useIsFocused();
{isFocused &&
<Camera
type={type}
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={{ flex: 1 }}
flashMode={flash}
zoom={zoom}
/>
}

React Native: setState triggers unwanted Tab change in Tab Navigator

Something does not make sense with my code.
I am using React Native to create a app.
In that app I am using a Tab Navigator.
It works fine until I call this.setState which for some reason triggers a unwanted Tab change from one tab to the other.
Why would setState trigger a Tab change??
This is my code:
import React from 'react';
import { StyleSheet, Text, View, FlatList, TextInput, StatusBar, Button } from 'react-native';
import { TabNavigator } from 'react-navigation';
import { Constants } from 'expo'
import { purple, white } from './utils/colors'
const R = require('ramda')
function CustomStatusBar({ backgroundColor, ...props }){
return (
<View style={{backgroundColor, height: Constants.statusBarHeight}}>
<StatusBar translucent backgroundColor={backgroundColor} {...props} />
</View>
)
}
export default class App extends React.Component {
constructor(props){
super(props)
this.handleDeckTitle = this.handleDeckTitle.bind(this)
}
state = {
title: ''
}
renderItem = (sample) => {
console.log('renderItem', sample)
return <Text>SAMPLE DATA</Text>
}
handleDeckTitle(e){
console.log('handleDeckTitle')
console.log('e', e)
console.log('this.state', this.state)
this.setState((prevState, props) => ({
title: e
}));
}
submitDeckTitle(){
console.log('submitDeckTitle')
}
render() {
console.log('R', R)
const Decks = () => {
return (
<View>
<CustomStatusBar backgroundColor={purple} barStyle='light-content' />
<Text>Decks!</Text>
</View>
)
}
const NewDeck = () => {
return (
<View>
<CustomStatusBar backgroundColor={purple} barStyle='light-content' />
<Text>What is the title of your new deck?</Text>
<TextInput style = {styles.input} onChangeText={this.handleDeckTitle}/>
<Button onPress={this.submitDeckTitle} title="Submit" />
</View>
)
}
const Tabs = TabNavigator({
Decks: {
screen: Decks
},
'New Deck': {
screen: NewDeck
},
});
return (
<Tabs />
);
}
}
const styles = StyleSheet.create({
container: {
paddingTop: 23,
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
input: {
margin: 15,
height: 40,
borderColor: '#7a42f4',
borderWidth: 1
},
});
I don't see what is wrong with this code.
In fact I think it should just work normally but it does not.
It triggers a tab change when I call handleDeckTitle which then calls this.setState
Got it to work now.
I changed the part that calls setState to be be a Separate Component with its own state.
Here is the code:
import React from 'react';
import { StyleSheet, Text, View, FlatList, TextInput, StatusBar, Button } from 'react-native';
import { TabNavigator } from 'react-navigation';
import { Constants } from 'expo'
import { purple, white } from './utils/colors'
const R = require('ramda')
function CustomStatusBar({ backgroundColor, ...props }){
return (
<View style={{backgroundColor, height: Constants.statusBarHeight}}>
<StatusBar translucent backgroundColor={backgroundColor} {...props} />
</View>
)
}
const Decks = () => {
return (
<View>
<CustomStatusBar backgroundColor={purple} barStyle='light-content' />
<Text>Decks!</Text>
</View>
)
}
class NewDeck extends React.Component {
constructor(props){
super(props)
this.handleDeckTitle = this.handleDeckTitle.bind(this)
}
state = {
title: ''
}
handleDeckTitle(e){
console.log('handleDeckTitle')
console.log('e', e)
console.log('this.state', this.state)
this.setState((prevState, props) => ({
title: e
}));
}
render(){
return (
<View>
<CustomStatusBar backgroundColor={purple} barStyle='light-content' />
<Text>What is the title of your new deck?</Text>
<TextInput style = {styles.input} onChangeText={this.handleDeckTitle}/>
<Button onPress={this.submitDeckTitle} title="Submit" />
</View>
)
}
}
const Tabs = TabNavigator({
Decks: {
screen: Decks
},
'New Deck': {
screen: NewDeck
},
});
export default class App extends React.Component {
constructor(props){
super(props)
// this.handleDeckTitle = this.handleDeckTitle.bind(this)
}
state = {
title: ''
}
renderItem = (sample) => {
console.log('renderItem', sample)
return <Text>SAMPLE DATA</Text>
}
submitDeckTitle(){
console.log('submitDeckTitle')
}
render() {
console.log('R', R)
return (
<Tabs />
);
}
}
const styles = StyleSheet.create({
container: {
paddingTop: 23,
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
input: {
margin: 15,
height: 40,
borderColor: '#7a42f4',
borderWidth: 1
},
});

Child component won't render from function

I am trying to render a child component using the function renderHowManyAlcohol()
The component LYDSelectNumber doesn't render, the correct props are being passed down, any ideas why this doesn't render?
render() {
return (
<Flexible>
<LYDSceneContainer
goBack={this.props.goBack}
subSteps={this.props.subSteps}>
<Flexible>
{this.renderHowManyAlcohol()}
</Flexible>
</LYDSceneContainer>
</Flexible>
);
}
renderHowManyAlcohol() {
return (
<View style={styles.HowManyAlcoholContainer}>
<Text>this renders</Text>
// this component below doesn't
<LYDSelectNumber
selectedNumberValue={this.props.selectedNumberValue}
onChangeNumber={this.props.onChangeNumber}
/>
</View>
);
}
LYDSelectNumber component, styles.container shows as a number '60', which is weird, I have the styles at the bottom of the page.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Picker, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import * as theme from '../../../theme';
const Item = Picker.Item;
export const SelectedNumber = ({ value = 0, displayPicker = () => {} } = {}) =>
<TouchableOpacity onPress={displayPicker}>
<View style={styles.centerWrap}>
<View style={styles.selectedNumberWrap}>
<Text style={styles.selectedNumberText}>
{value}
</Text>
</View>
</View>
</TouchableOpacity>;
class LYDSelectNumber extends Component {
static propTypes = {
onChangeNumber: PropTypes.func.isRequired,
numbersRange: PropTypes.array,
style: PropTypes.any,
selectedNumberValue: PropTypes.number,
};
static defaultProps = {
numbersRange: [18, 120],
style: undefined,
selectedNumberValue: undefined,
};
render() {
return (
<View style={styles.container}>
<SelectedNumber value={this.props.selectedNumberValue} />
<Picker
style={styles.picker}
selectedValue={this.props.selectedNumberValue}
onValueChange={this.props.onChangeNumber}>
{this._renderNumbers()}
</Picker>
</View>
);
}
_renderNumbers = () => {
const [firstNumber, lastNumber] = this.props.numbersRange;
let numbersItems = [];
let n = firstNumber;
while (n <= lastNumber) {
numbersItems.push(<Item key={n} label={`${n}`} value={n} />);
n++;
}
return numbersItems;
};
}
export default LYDSelectNumber;
const styles = StyleSheet.create({
container: {
flex: 3,
justifyContent: 'center',
alignItems: 'center',
},
picker: {
position: 'absolute',
top: 0,
width: 1000,
height: 1000,
},
centerWrap: {
alignItems: 'center',
},
selectedNumberWrap: {
width: theme.utils.responsiveWidth(40),
paddingBottom: 20,
borderBottomWidth: 2,
alignItems: 'center',
borderBottomColor: theme.colors.darkGranate,
},
selectedNumberText: {
...theme.fontStyles.selectedNumber,
},
});

Resources