React Navigation changing tab icons on tab navigator dynamically - react-native

So I am new to react native and redux. The app is already configured (by someone else) to have react-navigation and redux. Now we're using a TabNavigator (bottom) for our menu and this TabNavigator also contains the Login button. Now what I want to do is when the user logs in, the Login button (with text and icon) becomes Logout.
Is there a way to do that? Also my TabNavigator is in a separate file.
What I want is something like this:
TabNavigator(
{
...other screens,
//show this only if not logged in
Login: {
screen: LoginScreen
},
//show this only if logged in
Logout: {
screen: //There should be no screen here just the logout functionality
}
},
{...options here}
)
Thanks in advance.

You can do it using Redux:
AuthIcon.js:
const LOGGED_IN_IMAGE = require(...)
const LOGGED_OUT_IMAGE = require(...)
class AuthIcon extends React.Component {
render() {
const { loggedIn, focused, tintColor } = this.props
// loggedIn is what tells your app when the user is logged in, you can call it something else, it comes from redux
return (
<View>
<Image source={loggedIn ? LOGGED_IN_IMAGE : LOGGED_OUT_IMAGE} resizeMode='stretch' style={{ tintColor: focused ? tintColor : null, width: 21, height: 21 }} />
</View>
)
}
}
const ConnectedAuthIcon = connect(state => {
const { loggedIn } = state.auth
return { loggedIn }
})(AuthIcon)
export default ConnectedAuthIcon;
then inside your TabNavigator file:
import ConnectedAuthIcon from './AuthIcon.js'
export default TabNavigator({
Auth: {
screen: Auth,
navigationOptions: ({ navigation }) => ({
tabBarLabel: null,
tabBarIcon: ({ tintColor, focused }) => <ConnectedAuthIcon tintColor={tintColor} focused={focused} />,
title: "Auth"
})
}
})
Edit:
In your Auth.js:
class Auth extends React.Component {
render() {
const { loggedIn } = this.props
if (loggedIn) {
return <Profile />
} else {
return <Login />
}
}
}
export default connect(state => {
const { loggedIn } = state.auth
return { loggedIn }
})(Auth)

Related

How do I create an embedded Stack navigator inside a React Native formSheet modal?

Like so:
I'm running react-navigation v4.
First you have to follow the tutorial on how to set up a react-navigation modal, the one that has a jump animation and doesn't look like the native formSheet. You have to set up a stack navigator with your root navigator as one child and the modal as another:
And it scales, because you can have more than one of these modals as children.
The code for this is the following:
const RootNavigator = createStackNavigator(
{
index: { screen: AppNavigator },
[NC.SCREEN_ROOM_INFO]: { screen: RoomInfoNavigator },
[NC.SCREEN_CHAT_CREATE]: { screen: RoomCreateNavigator },
[NC.SCREEN_CHAT_SEARCH]: { screen: ChatSearchNavigator },
[NC.SCREEN_CHAT_GIF_PICKER]: { screen: GifPickerNavigator }
},
{
mode: 'modal',
headerMode: 'none',
transitionConfig: () => ({
transitionSpec: {
duration: 0
}
}),
transparentCard: true
}
)
Then you need to implement these, from my example, 4 navigators that will be displayed as modals each like so:
// Here you'll specify the screens you'll navigate in this modal, starting from index.
const RoomInfoStack = createStackNavigator({
index: { screen: NavigableRoomInfo },
[NC.SCREEN_ROOM_ROSTER]: { screen: NavigableRoomRoster },
[NC.SCREEN_ROOM_NOTIFICATION_PREFERENCES]: { screen: NavigableRoomNotificationPreferences },
[NC.SCREEN_ROOM_EDIT]: { screen: NavigableRoomEdit }
})
type NavigationComponent<T = any> = {
navigation?: NavigationScreenProp<NavigationState, T>
}
type Props = NavigationComponent
// THIS code is from the react-navigation tutorial on how to make a react-navigation modal:
// https://reactnavigation.org/docs/4.x/custom-navigators/#extending-navigators
class RoomInfoNavigator extends React.Component<Props> {
static router = {
...RoomInfoStack.router,
getStateForAction: (action, lastState) => {
// check for custom actions and return a different navigation state.
return RoomInfoStack.router.getStateForAction(action, lastState)
}
}
constructor(props) {
super(props)
this.onClose = this.onClose.bind(this)
}
onClose() {
this.props.navigation?.goBack()
}
// And here is the trick, you'll render an always open RN formSheet
// and link its dismiss callbacks to the goBack action in react-navigation
// and render your stack as its children, redirecting the navigator var to it in props.
render() {
return (
<Modal
visible={true}
animationType={'slide'}
supportedOrientations={['portrait', 'landscape']}
presentationStyle={'formSheet'}
onRequestClose={() => this.onClose()}
onDismiss={() => this.onClose()}
>
<RoomInfoStack {...this.props} />
</Modal>
)
}
}
export { RoomInfoNavigator }
This export is what our root stack imported before. Then you just need to render the screens, I have a pattern that I do to extract the navigation params to props in case this screen is ever displayed without navigation:
const NavigableRoomInfo = (props: NavigationComponent<RoomInfoProps>) => {
const roomInfo = props.navigation!.state!.params!.roomInfo
const roomInfoFromStore = useRoomFromStore(roomInfo.id)
// Here I update the navigation params so the navigation bar also updates.
useEffect(() => {
props.navigation?.setParams({
roomInfo: roomInfoFromStore
})
}, [roomInfoFromStore])
// You can even specify a different Status bar color in case it's seen through modal view:
return (
<>
<StatusBar barStyle="default" />
<RoomInfo roomInfo={roomInfoFromStore} navigation={props.navigation} />
</>
)
}
Sources:
https://reactnavigation.org/docs/4.x/modal
https://reactnavigation.org/docs/4.x/custom-navigators/#extending-navigators

Combine React Navigation 3.0 and JWT to determine initialRouteName based on auth state

I am trying to make a normal App.js component integrated with JWT client to behave correctly when integrating React Navigator 3.0
Unfortunately I can only make work one or the other, not both. My issue is that React Navigator sort of hijacks App.js and determines the initial route instead of the usual App component render.
Here is my code so far:
App.js
import React, { Component } from 'react';
import { createAppContainer,
createBottomTabNavigator,
} from 'react-navigation';
import Auth from './src/screens/Auth';
import HomeScreen from './src/screens/HomeScreen';
class App extends Component {
constructor() {
super();
this.state = {
jwt: '',
};
}
render() {
if (!this.state.jwt) {
return (
<Auth />
);
} else if (this.state.jwt) {
return (
<HomeScreen />
);
}
}
}
const TabNavigator = createBottomTabNavigator({
Home: { screen: HomeScreen,
navigationOptions: {
tabBarLabel: 'Home',
}
},
Auth: { screen: Auth,
navigationOptions: {
tabBarLabel: 'Auth',
}
},
},
{ initialRouteName: App.state.jwt ? 'Home' : 'Auth' }
);
export default createAppContainer(TabNavigator);
As you can see, my issue is with this line:
{ initialRouteName: App.state.jwt ? 'Home' : 'Auth' }
How can I get the JWT state inside the TabNavigator component so I can define the correct initialRouteName?
this.state.jwt and App.state.jwt obviously do not work, and I tried (and failed) to pass the state to the TabNavigator object as a prop.
Any help is appreciated.
This is the correct method:
First you set get the Auth token and save its state in App.js. Then you pass the state as screenProps to the Navigation object:
export default class App extends React.Component {
constructor() {
super();
this.state = {
jwt: '',
loading: true
};
this.newJWT = this.newJWT.bind(this);
this.deleteJWT = deviceStorage.deleteJWT.bind(this);
this.loadJWT = deviceStorage.loadJWT.bind(this);
this.loadJWT();
}
state = {
isLoadingComplete: false,
};
newJWT(jwt) {
this.setState({
jwt: jwt
});
}
render() {
if (this.state.loading) {
return (
<Loading size={'large'} />
);
} else if (!this.state.jwt) {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<TabNavigator screenProps={{setToken: this.newJWT }} />
</View>
);
}
The navigation object passes it on to the screens that need it.
const TabNavigator = createMaterialTopTabNavigator(
{
Profile: {
screen: props => <ProfileScreen {...props.screenProps} />,
navigationOptions: {
//tabBarLabel: 'Perfil',
title: 'Header Title',
tabBarIcon: ({ tintColor, focused }) => (
<Ionicons
name={focused ? 'ios-person' : 'ios-person'} //TODO change to focused icon
size={26}
style={{ color: tintColor }}
/>
),
}
},
A you can see the props can passed on as ScreenProps and then read in the child component (screen) like this:
export default class ProfileScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
email: '',
username: '',
phone: '',
password: '',
name: '',
error: ''
};
}
componentDidMount() {
const headers = {
Authorization: this.props.jwt
};
api.get('/user')
.then((response) => {
this.setState({
email: response.data.data.attributes.email,
phone: response.data.data.attributes.phone,
username: response.data.data.attributes.username,
name: response.data.data.attributes.name,
loading: false
});
}).catch((error) => {
this.setState({
error: 'Error retrieving data',
loading: false
});
});
}
I suppose this would be far simpler with Redux but I'm still learning that.
May i ask that did you include login screen for authentication?

React Navigation - Tab Navigation - Getting different screens from only one class

It is possible to change between tabs without having more then one class?
On my code I have a class that returns multiple components, and I want my TabNavigator to switch between these componentes, not between classes like they have in the React Navigation docs (https://reactnavigation.org/docs/tab-based-navigation.html).
class Monument extends Component{
render(){
const {navigate} = this.props.navigation;
const { data } = this.props.navigation.state.params;
return (
<MonumentMaker category={'Castelos'} navigate={navigate} data={data}/>
<MonumentMaker category={'Museus'} navigate={navigate} data={data}/>
<MonumentMaker category={'Igrejas'} navigate={navigate} data={data}/>
<MonumentMaker category={'Locais de Interesse'} navigate={navigate} data={data}/>
);
}
}
export default TabNavigator({
Convento: {
screen:**first component**
},
Museus: {
screen:**second component**
},
Igrejas: {
screen:**third component**
},
OutrosLocais: {
screen:**forth component**
}
})
It is possible what I want to accomplish?
Thank you for your help!
You can make your TabNavigation as follows
const myTabNavigator = TabNavigator({
Convento: {
screen: { screen: props => <Monument {...props} {...myProps} /> }
},
Museus: {
screen: { screen: props => <Monument {...props} {...myProps} /> }
},
Igrejas: {
screen: { screen: props => <Monument {...props} {...myProps} /> }
},
OutrosLocais: {
screen: { screen: props => <Monument {...props} {...myProps} /> }
}
})
Monument.js
const Monument = ({...props}, {...myProps}) => (
<View>
{...// More stuff}
</View>
)

How to handle click event on tab item of TabNavigator in React Native App using react-navigation?

I am programming React Native App. I am using react-navigation for navigating screens.
I have 2 Stack Navigators, they are stayed in a Tab Navigator. I want handle click event when I press tab item on TabBar to refresh its view.
export const HomeStack = StackNavigator({
Home: {screen: ScreenHome},
Detail: {screen: ScreenDetail}
})
export const UserStack = StackNavigator({
User: {screen: ScreenUser}
})
export const Tabbar = TabNavigator({
HomeTab: {
screen: HomeStack,
},
UserTab: {
screen: UserStack,
}
}, {
tabBarComponent: ({ jumpToIndex, ...props}) => (
<TabBarBottom
{...props}
jumpToIndex={(index) => {
if(props.navigation.state.index === index) {
props.navigation.clickButton(); //----> pass props params (code processes)
}
else {
jumpToIndex(index);
}
}
}
/>
),
tabBarPosition: 'bottom'
});
class TabClass extends Component{
constructor(props){
super(props)
this.clickButton = this.clickButton.bind(this)
}
clickButton(){
console.log('click button')
}
render (){
return (
<Tabbar clickButton={()=> this.clickButton()}/>
)
}
}
I want to pass clickButton() function from TabClass Component to the code which processes event click tab bar. When if(props.navigation.state.index === index), I want it will call clickButton(). I try it but it doesn't work.
Is there any way to solve my matter?
I tried onNavigationStateChange(prevState, currentState).
class TabClass extends Component{
constructor(props){
super(props)
this.clickButton = this.clickButton.bind(this)
}
clickButton(){
console.log('click button')
}
_handleNavagationStateChange(prevState, currentState){
console.log('handle navigation state change')
}
render (){
return (
<Tabbar onNavigationStateChange={(prevState, currentState) => {
this._handleNavagationStateChange(prevState, currentState)
}}
clickButton={()=> this.clickButton()}
/>
)
}
}
However, _handleNavagationStateChange(prevState, currentState) only run when navigation state changes (for examples, if I stay at HomeTab, I click User Tab Item, this function will run; if I stay at HomeTab, I click Home Tab Item, this function will not run).
Is there any way to handle click event on tab item.
according to the newest documentation here, you can use navigationOptions: {navigationOptions: () => doWhatever()} to handle tab bar taps.
From the react-navigation 4.x docs, you can override tabBarOnPress within navigationOptions:
tabBarOnPress: ({ navigation, defaultHandler }) => {
defaultHandler(); // Call the default handler to actually switch tabs
// do extra stuff here
},
Please try the code following when customize the event touch of TabBar:
import { TabBarBottom, TabNavigator, StackNavigator } from 'react-navigation';
export const MainScreenNavigator = TabNavigator({
Home: { screen: HomeViewContainer },
Search: { screen: SearchViewContainer },
}, {
tabBarComponent: ({ jumpToIndex, ...props, navigation }) => (
<TabBarBottom
{...props}
jumpToIndex = { tabIndex => {
const currentIndex = navigation.state.index;
if (tabIndex == 1) {
// do some thing. Call Native Live Stream Record
} else {
jumpToIndex(tabIndex);
}
console.log('Select tab: ', tabIndex);
}}
/>),
tabBarPosition: 'bottom',
});

React native navigation class function in header

I've got a problem with react native navigation and nested navigators.
Basically, the nested navigators (tab in a page) work pretty well. But when i add a button in the header with the _saveDetails function, it throw me an undefined function if i'm in the Players tab, and it works well when i'm on the Teams tab
Does anyone have an idea of what am i doing wrong? Thanks.
class HomeScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
headerRight: <Button title="Save" onPress={() =>
params.handleSave()} />
};
};
_saveDetails() {
console.log('clicked save');
}
componentDidMount() {
this.props.navigation.setParams({ handleSave: this._saveDetails });
}
render() {
return (
<View />
);
}
}
const MainScreenNavigator = TabNavigator({
Players: { screen: HomeScreen},
Teams: { screen: HomeScreen},
});
const SimpleApp = StackNavigator({
Home: { screen: MainScreenNavigator },
Player: { screen: PlayerPage },
});
Please try this one and let me know if you fetch any other problem. Just convert your code according to below code.
static navigationOptions = {
header: (navigation, header) => ({
...header,
right: (
navigation.navigate('Settings')}>
Settings
)
})
}
Thanks
Just change your code become like this
class HomeScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
// const { params = {} } = navigation.state; //delete this
return {
headerRight: <Button title="Save" onPress={() =>
navigation.state.params.handleSave()} /> // add navigation.state
};
};
.....