react-navigation-is-focused-hoc
Welcome React Navigation user seeking focus 😀
This is a quick, ready to use solution using HOC to expose props.isFocused
. No Redux needed
Installation
- Install the latest version of
react-navigation
- Install the latest version of
@patwoz/react-navigation-is-focused-hoc
from npm
yarn add @patwoz/react-navigation-is-focused-hoc
or
npm install --save @patwoz/react-navigation-is-focused-hoc
Full Usage Example
To see more of the react-navigation-is-focused-hoc
in action, you can check out the source in ExampleNavigation folder.
Usage
app.js
import React from 'react'
import { StackNavigator } from 'react-navigation'
import { updateFocus, getCurrentRouteKey } from '@patwoz/react-navigation-is-focused-hoc'
import MyScreenView from './screens/myScreenView'
const AppNavigator = StackNavigator({
MyScreenView: { screen: MyScreenView },
}, {
initialRouteName: 'MyScreenView',
})
export default class App extends React.Component {
render() {
return (
<AppNavigator
onNavigationStateChange={(prevState, currentState) => {
// If you want to ignore the state changed from `DrawerNavigator`, use this:
/*
if (/^Drawer(Open|Close|Toggle)$/.test(getCurrentRouteKey(newState)) === false) {
updateFocus(newState);
return;
}
*/
updateFocus(currentState)
}}
/>
)
}
}
myScreenView.js
import React from 'react'
import PropTypes from 'prop-types'
import {
View,
Text,
} from 'react-native'
import { withNavigationFocus } from '@patwoz/react-navigation-is-focused-hoc'
class MyScreenView extends React.Component {
static propTypes = {
isFocused: PropTypes.bool.isRequired,
focusedRouteKey: PropTypes.string.isRequired,
};
componentWillReceiveProps(nextProps) {
if (!this.props.isFocused && nextProps.isFocused) {
}
if (this.props.isFocused && !nextProps.isFocused) {
}
}
shouldComponentUpdate(nextProps) {
if (this.props.isFocused && !nextProps.isFocused) {
return true;
}
if (!this.props.isFocused && !nextProps.isFocused) {
return false;
}
return !this.props.isFocused && nextProps.isFocused;
}
render() {
if (!this.props.isFocused ) {
return null;
}
return (
<View>
{this.props.isFocused
? <Text>I am focused</Text>
: <Text>I am not focused</Text>
}
</View>
)
}
}
export default withNavigationFocus(MyScreenView)
Thanks to Adam (@skevy), Mike (@grabbou), Satyajit (@satya164) and others for the react-navigation
module