How to use BackHandler in react-native-router-flux with tabbar - react-native

Im trying to implement Backhandler with Listener, In componentWillMount im adding the listener and in componentWillUnMount im removing the listener but componentWillUnMount is not called when we push to other component. So Listener is there in other Components also, Is there a problem of react-native-router-flux with tabbar

To make back handler work with a centralised configuration, I'd normally have the handler in a component called AppNavigation which is the parent for Router component.
It looks something like:
<AppNavigation>
<Router>
<Scene key="root">
{/* other scenes */}
</Scene>
</Router>
</AppNavigation>
Handling the back button in AppNavigation would then be relatively straightforward:
import React, {Component} from "react";
import {BackAndroid} from "react-native";
import {Actions} from "react-native-router-flux";
class AppNavigation extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
//listens to hardwareBackPress
BackAndroid.addEventListener('hardwareBackPress', () => {
try {
Actions.pop();
return true;
}
catch (err) {
console.debug("Can't pop. Exiting the app...");
return false;
}
});
}
componentWillUnmount(){
console.log("Unmounting app, removing listeners");
BackAndroid.removeEventListener('hardwareBackPress');
}
render() {
return this.props.children;
}
}
export default AppNavigation;
P.S. Don't forget to differentiate between android and iOS though, since I believe iOS does not have a back button.

Related

Context API w/ React Navigation (React Native)

I'm trying to wrap my mind around using Context in my React Native app that uses React Navigation. I think I am way off on this one. I am simply trying to pass the name of a book to my entire app through the navigation stacks.
App.js
const BookContext = React.createContext();
class BookProvider extends Component {
state = {
name: 'book name'
}
render() {
return (
<BookContext.Provider value={{
name: this.state.name
}}>
{this.props.children}
</BookContext.Provider>
)
}
}
export default function App() {
return (
<BookProvider>
<BookContext.Consumer>
{({ name }) => (<Routes name={name} />)} //my react navigation stacks component
</BookContext.Consumer>
</BookProvider>
);
}
and in Book.js (a component in the navigation stack)
componentDidMount() {
console.log(this.context)
}
returns an empty object {}
Any help is appreciated!
To save you some Googling, this is the correct approach: https://github.com/react-navigation/react-navigation/issues/935#issuecomment-359675855
Another way, if you're using a relatively new version of React, and your component in question at that route is a functional component, is to use the useContext React hook.
e.g.
import React, { useContext } from 'react'
import { BookContext } from '/path/to/BookContext'
function BookConsumerComponent() {
const { name } = useContext(BookContext);
console.log(name);
}

How to set the title of the scene that's a child of a tab using react-native-router-flux

I've this route:
export default props => (
<Router>
<Stack key="root" hideNavBar>
<Tabs key='tabs'
tabs={true}
initial
tabBarStyle={{backgroundColor: THEME_NAVBAR_AND_TABBAR}}
showLabel={false}>
<Scene key='events' component={Events} title='Events' icon={TabIcon}/>
</Tabs>
</Stack>
</Router>
)
On my Events components, I've this:
import React from 'react'
import {View, Text, ScrollView, TouchableWithoutFeedback,
TouchableOpacity} from 'react-native'
import {connect} from "react-redux"
import style from './style'
import {Actions} from "react-native-router-flux";
class Events extends React.Component {
constructor(props) {
super(props)
this.state = {
loaded: false
}
}
componentDidMount() {
Actions.refresh({ title: 'xxxx' })
}
render() {
return (
<ScrollView style={style.scene}>
</ScrollView>
)
}
}
const mapStateToProps = state => (
{
events: state.ContentReducer.events
}
)
export default connect(mapStateToProps,
{
})(Events)
But it's being ignored. Probably because the scene is a child of the Tabs. How to make this change ? (it must me inside the component - cannot be on the router)
After many research and trial/errors, I found a solution:
this.props.navigation.setParams({
title: 'xxxx'
})
This happens because the tabs by default load all scenes nested, you can pass the props "lazy" to prevent that. But if you open the scene one time you will need to use componentWillReceiveProps to get the new props, because the scene will stand open even if you change the tab.
On Events component scene you can use the title as a state then use componentWillMount function to get the title and componentWillReceiveProps function to get the new title when it changes.
componentWillMount() {
this.setState({title: this.props.title});
}
componentWillReceiveProps(newProps) {
//new title
this.setState({title: newProps.title});
}

Navigation.goBack() with an API call in React-Native

In my application, I have few cases where navigation.goBack() cannot be used. I use react-navigation for navigation. When i'm in the detail screen, When I go back, I want to send an API call to get the latest records to the parent screen. So I used, navigation.navigate() instead of navigation.goBack(); But, this makes my app slow if I navigate and navigate back few times. It gets very slow if I do this few more times. What is the reason behind this? How the navigation.navigate() differs from navigation.goBack()?
What is the preferred way of handling this kind of scenario?
is there a way to pass param from navigate.goback() and parent can listen to the params and update its state?
You can pass a callback function as parameter (as mentioned in other answers).
Here is a more clear example, when you navigate from A to B and you want B to communicate information back to A you can pass a callback (here onSelect):
ViewA.js
import React from "react";
import { Button, Text, View } from "react-native";
class ViewA extends React.Component {
state = { selected: false };
onSelect = data => {
this.setState(data);
};
onPress = () => {
this.props.navigate("ViewB", { onSelect: this.onSelect });
};
render() {
return (
<View>
<Text>{this.state.selected ? "Selected" : "Not Selected"}</Text>
<Button title="Next" onPress={this.onPress} />
</View>
);
}
}
ViewB.js
import React from "react";
import { Button } from "react-native";
class ViewB extends React.Component {
goBack() {
const { navigation } = this.props;
navigation.goBack();
navigation.state.params.onSelect({ selected: true });
}
render() {
return <Button title="back" onPress={this.goBack} />;
}
}
Hats off for debrice - Refer to https://github.com/react-navigation/react-navigation/issues/288#issuecomment-315684617

Keyboard listener is running more then once

Hey I'm trying to create an event that will fire when the keyboard shows up but the function is firing more then once, I don't know why ..
import React, { Component } from 'react';
import { Keyboard, Alert, View, TextInput } from 'react-native';
export default class App extends Component {
constructor(props: any) {
super(props);
this.kbDidShowListener = Keyboard.addListener('keyboardDidShow', () => Alert.alert('keyboard is up'));
}
componentWillUnmount() {
this.kbDidShowListener.remove();
}
render() {
return (
<View style={{ marginTop: 30 }}>
<TextInput />
</View>
);
}
}
here is an expo for the example (you will see the alert more then once)
https://snack.expo.io/H1DHaIdgM
p.s I'm working on Android.
thanks!
The render function does not run only once. Usually refreshes multiple times too, while calculating the state and props. That could explain the issue.
If you want to be sure, try adding a console too inside the render method, to see if the numbers match.
Actually, another thing I am thinking. Try moving the code to the componentWillMount or componentDidMount
componentDidMount(){
this.kbDidShowListener = Keyboard.addListener('keyboardDidShow', () => Alert.alert('keyboard is up'));
}

Disable rotation for specific views in react native

How can I disable rotation only for specific views (e.g: when using Navigator) and not for the entire app?
The question here already addresses disabling rotation for the entire app
With the react-native-orientation package, it's possible to lock the orientation to portrait/landscape. The package and documentation can be found here: https://github.com/yamill/react-native-orientation
Remember; you should not put your locking inside the rendering of scenes (nor the renderScene method). Since the Navigator re-renders all the scenes in the route stack, this would probably cause weird side effects for you. Rather, the locking/unlocking should be put in the code that interacts with the route stack (ie. calls the push/pop methods).
If your case is about more specific control over orientations of different screens in StackNavigator (something like Portrait -> LandscapeLeft -> LandscapeRight -> Portrait, and all the way back), here is a may-not-that-pretty solution:
packages needed: react-navigation, react-native-orientation;
define base screens as follow:
// baseScreen.js
import React, { Component } from "react";
import Orientation from "react-native-orientation";
export class PortraitScreen extends Component {
constructor(props) {
super(props);
this._willFocusSubscription = this.props.navigation.addListener("willFocus", payload => {
// lock to portrait when this screen is about to appear
Orientation.lockToPortrait();
})
}
componentWillUnmount() {
// remove subscription when unmount
this._willFocusSubscription.remove();
}
}
export class LandscapeScreen extends Component {
constructor(props) {
super(props);
this._willFocusSubscription = this.props.navigation.addListener("willFocus", payload => {
// lock to landscape
Orientation.lockToLandscape();
})
}
componentWillUnmount() {
// remove subscription either
this._willFocusSubscription.remove();
}
}
define concrete screens which extends abovementioned base screen(s):
// moduleScreens.js
import React from "react";
import { Button, View } from "react-native";
import { PortraitScreen, LandscapeScreen } from "/path/to/baseScreen";
export class VideoDescScreen extends PortraitScreen {
render() {
return (
<View>
<Button
title="watch video"
onPress={() => this.props.navigation.navigate("VideoPlayer")}
/>
</View>
)
}
}
export class VideoPlayerScreen extends LandscapeScreen {
render() {
return <View>...</View>
}
}
create route like this:
// route.js
import React from "react";
import { createStackNavigator } from "react-navigation";
import { VideoDescScreen, VideoPlayerScreen } from "/path/to/moduleScreens";
const stack = createStackNavigator(
{
VideoDesc: {
screen: VideoDescScreen
},
VideoPlayer: {
screen: VideoPlayerScreen
}
}
)
How it works? According to doc, we observe event willFocus when screen is initialized, and each time this screen is about to appear (focused) in navigation, we lock device to our desired orientation, works for both PUSH(to) and POP(back from) behaviors.
Hope it helps.