React native set state from drawer navigator to other component - react-native

On first screen I have a component having some listing of products say ProductListing.js. And on drawer navigator I have some check boxes. I want to set state of ProductListing.js when I am clicking on any check box of navigator.
App.js
import React, {Component} from 'react';
import Router from './src/config/routes';
export default class App extends React.Component {
render () {
return (
<Router/>
);
}
}
Router.js
export default DrawerNavigator({
Dashboard: {screen: Dashboard},
CreateLogin: {screen: CreateLogin},
Test: {screen: Test}
}, {
contentComponent: SideMenu,
drawerWidth: 300,
drawerPosition: 'right'
});
SideMenu.js
render () {
const { data, searchTerm, searchAttribute, ignoreCase, checked } = this.state;
return (
<View style={styles.container}>
<ScrollView>
<View>
<TextInput
style={styles.search} placeholder={"Search"}
onChangeText={searchTerm => this.setState({ searchTerm })} />
<SearchableFlatList
data={data} searchTerm={searchTerm}
searchAttribute={searchAttribute} ignoreCase={ignoreCase}
renderItem={({ item, index }) => <CheckBox
title={item.name +' ('+ item.count+')'}
onPress={() => this.handleChange(item.id)}
checked={checked[item.id]} />
}
keyExtractor={({id}, index) => index.toString()} />
</View>
</ScrollView>
<View style={styles.footerContainer}>
<Text>Apply filter by choosing filter values</Text>
</View>
</View>
);
}
}
ProductListing.js
constructor(props){
super(props);
this.state ={ isLoading: true,isloadmore: false, page :1,dataSource: [],countryFilter:0, gradesFilter:'',country:'',totalRecord:0};
}
render(){
const { navigation } = this.props;
return(
<View style={{flexDirection:'column',paddingRight:8}}>
<Button
title='Filter'
buttonStyle={{backgroundColor:'#000000',borderRadius:2}}
onPress={() => navigation.dispatch(DrawerActions.openDrawer())}
/>
</View>
);
}
Now on click of handleChange in SideMenu.js I want to update state of gradesFilter in ProductListing.js where I am updating my product listing.

You can easily achieve this with a portal! Take a look here.

You can pass the parameters from drawer to the Product screen via navigation params.
For this, you need to stackNavigator inside your DrawerNavigator like:
Router:
const MyStack = StackNavigator({
Dashboard: {screen: Dashboard},
CreateLogin: {screen: CreateLogin},
Test: {screen: Test}
});
const MyDrawer = DrawerNavigator({
Main: { screen: MyStack }
},
{
contentComponent: SideMenu,
drawerWidth: 300,
drawerPosition: 'right'
});
export const Router = StackNavigator({
Login: {screen: Login},
Drawer: {
screen: MyDrawer,
navigationOptions: { header: null } } //prevent double header
});
Now you can navigate and pass parameter from login or Dashboard or anyother screen via Drawer like
_login() {
this.props.navigation.navigate('Drawer', { parameter: userName });
}
And to use this parameter you need to access:
const { parameter } = this.props.navigation.state.params;
which you can further use to set state like
this.setState({
productSelection: parameter)};
Another approach can be via, listener/ Callback handler.

Related

How do I conditionally render a header in a Stack Navigator for React Native Navigation?

I would like my initial page to NOT contain a header. However, I would like a header to appear on each subsequent page. Right now my current stackNavigator looks like this:
const AppNavigator = createStackNavigator(
{
HomeScreen: HomePage,
SecondPage: SecondPage,
Account: Account,
About: About,
},
{
initialRouteName: 'HomeScreen',
headerMode: 'none',
navigationOptions: {
headerVisible: false,
},
},
);
export default createAppContainer(AppNavigator);
Here is the basic boilerplate for my second page:
const SecondPage: () => React$Node = () => {
return (
<>
<StatusBar barStyle="dark-content" />
<View style={styles.body}>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>This is the Secondpage</Text>
</View>
</View>
</>
);
};
export default SecondPage;
You have three ways of doing this using navigationOptions:
1) Directly when you define your navigator:
createStackNavigator({
{
HomeScreen: {
screen : HomePage,
navigationOptions: {header : null}
},
SecondPage: SecondPage,
Account: Account,
About: About,
},
{ ... } //your navigationOptions
})
2) Directly inside the screen as said by Shashank Malviya. Only if you aren't using a functional component.
3) Return defaultNavigationOptions as a function and use navigation state:
createStackNavigator({
{ ... }, //your RouteConfigs
{
initialRouteName: 'HomeScreen',
headerMode: 'none',
defaultNavigationOptions : ({navigation}) => navigation.state.routeName === "HomePage" && {header: null}
},
})
Can be written on every component before render
static navigationOptions = ({ navigation }) => {
const { state } = navigation
return {
headerVisible: true // can be true or false
}
}

React Navigation drawer doesn't display the title of the current page

I created 2 pages namely Home and Profile and added these two pages to createDrawerNavigation. And then added this drawer navigation to a stack navigator. Now when I try to display the title on the header of the current page. I'm unable to do it.
Here is my code.
Tried DefaultNavigationOptions and got the props value of navigator but doesn't work that way.
const MenuStack = createDrawerNavigator(
{
HomePage: {
screen: Home
},
ProfilePage: {
screen: Profile
}
},
{
drawerWidth: Math.round(Dimensions.get("window").width) * 0.75,
contentOptions: {
activeTintColor: theme.colors.accent
}
}
);
const AppStack = createStackNavigator(
{
MenuStack: {
screen: MenuStack
}
},
{
defaultNavigationOptions: ({ navigation }) => {
return {
headerLeft: (
<Icon
style={{ paddingLeft: 10 }}
onPress={() => navigation.toggleDrawer()}
name="bars"
size={30}
/>
),
headerRight: (
<Icon
style={{ paddingRight: 10 }}
onPress={() => navigation.toggleDrawer()}
name="search"
size={30}
/>
),
headerTitle: navigation.state.routeName,
headerStyle: {
backgroundColor: theme.colors.accent
}
};
}
}
);
export const createRootNavigator = (signedIn = false) => {
return createAppContainer(
createSwitchNavigator(
{
SignedIn: {
screen: AppStack
},
SignedOut: {
screen: WelcomeStack
},
SignInAndOut: {
screen: AuthStack
}
},
{
initialRouteName: signedIn ? "SignedIn" : "SignedOut"
}
)
);
};
I added a headerTitle property in the createStackNavigator but I tell the "menustack" as the title for every page.
Expected the title of the page on the header.
You have 2 options:
1. Render your own header component in each screen
You can render a header inside your screens, either a custom one or one from a component library such as react native paper.
function Home() {
return (
<React.Fragment>
<MyCustomHeader title="Home" />
{{ /* screen content */ }}
</React.Fragment>
);
}
2. Create a stack navigator for each screen that needs to have header
const MenuStack = createDrawerNavigator({
HomePage: {
screen: createStackNavigator({ Home })
},
ProfilePage: {
screen: createStackNavigator({ Profile })
}
});
Keep in mind that while this requires less code, it's also less performant.

How to pass a prop to all tabs of a createBottomTabNavigator

My application is calling a createBottomTabNavigator from a createSwitchNavigator using the following this.props.navigation.navigate('AppMenu', {UserName: 'First Name'}); The createBottomTabNavigator consists of 2 tabs, one is a Stack Navigator and the second is just a React component. When I navigate to the initialRouteName of the Stack Navigator the prop I passed in is available, but if I select the second tab of the Tab Navigator the prop is not available.
Is there a way I can pass a prop to all tabs of a Bottom Tab Navigator when it is rendered?
Here is a diagram of the applications, and sample code that can be run in Snack.
import React from 'react';
import { Text, View, Button } from 'react-native';
import { createBottomTabNavigator, createStackNavigator, createSwitchNavigator } from 'react-navigation';
class LoginScreen extends React.Component {
_navToMain = () => {
console.log('Login Screen: Passing user: First Name');
this.props.navigation.navigate('AppMenu', {UserName: 'First Name'});
}
render () {
return (
<View style={{flexDirection: 'column', paddingTop:20}}>
<Text>Pass UserName prop to createBottomTabNavigator</Text>
<Button title='Login!' onPress={this._navToMain}/>
</View>
)
}
}
class SyncScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerTitle: 'Sync Screen',
};
};
render () {
return (
<View style={{flexDirection: 'column', paddingTop:20}}>
<Text>Sync Screen Navigation Prop UserName (missing!): {JSON.stringify(this.props.navigation.getParam('UserName'))}</Text>
<Button title='Test Button' onPress={() => {}} />
</View>
);
}
}
class AppMenuScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerTitle: 'Stack Navigator',
};
};
_navToOne = () => {
console.log('Going to Stack One')
this.props.navigation.navigate('StackOne', {UserName: this.props.navigation.getParam('UserName')});
}
render () {
return (
<View style={{flexDirection: 'column'}} >
<Text>App Menu Navigation Prop UserName passed from SwitchNavigator: {JSON.stringify(this.props.navigation.getParam('UserName'))}</Text>
<Button title='Screen one' onPress={this._navToOne} />
</View>
)
}
}
class StackOneScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerTitle: 'Stack One Screen',
};
};
render () {
return (
<View style={{flexDirection: 'row'}} >
<Text>Stack One Screen Navigation Props: {JSON.stringify(this.props.navigation.getParam('UserName'))}</Text>
</View>
)
}
}
const AppStack = createStackNavigator(
{
AppMenu: AppMenuScreen,
StackOne: StackOneScreen,
},
{
initialRouteName: "AppMenu",
navigationOptions: {
headerTintColor: "#a41034",
headerStyle: {
backgroundColor: "#fff"
}
}
}
);
const MainTabs = createBottomTabNavigator(
{
'Apps': { screen: AppStack },
'Sync': { screen: SyncScreen },
},
{
navigationOptions: ({ navigation }) => ({
title: navigation.state,
tabBarIcon: ({ focused, horizontal, tintColor }) => {
const { routeName } = navigation.state;
}
}),
tabBarOptions: {
activeTintColor: 'red',
inactiveTintColor: 'gray',
tabBackgroundColor: 'black',
labelStyle:{
fontSize: 24,
marginBottom:10,
}
},
animationEnabled: true,
swipeEnabled: false,
}
);
const AppNavigator = createSwitchNavigator(
{
Login: LoginScreen,
Main: MainTabs
},
{
initialRouteName: 'Login',
backBehavior: "initialRoute",
}
);
export default class App extends React.Component {
render() {
return (
<AppNavigator />
);
}
}
Package.json
"react": "16.5.0",
"react-native": "0.57.1",
"react-navigation": "^2.0.0"
you can pass props on navigate using
_navToOne = () => {
console.log("Going to Stack One");
this.props.navigation.navigate({
routeName: "StackOne",
params: { UserName: this.props.navigation.state.params.UserName }
});
};
if you want to access props passed using navigate
this.props.navigation.state.params.PROPNAME
// PROPNAME is the prop you passed and want to get
It's just a temporary solution, at least these code can solve your issue
When I navigate to the initialRouteName of the Stack Navigator the prop I passed in is available, but if I select the second tab of the Tab Navigator the prop is not available
because you just sent the param into AppMenu using this.props.navigation.navigate('AppMenu', {UserName: 'First Name'});
UserName is available on both of tab after i change the code of LoginScreen class :
class LoginScreen extends React.Component {
_navToMain = () => {
console.log('Login Screen: Passing user: First Name');
//-------add this-------
this.props.navigation.navigate('Sync', {UserName: 'First Name'});
//----------------------
this.props.navigation.navigate('AppMenu', {UserName: 'First Name'});
}
render () {
return (
<View style={{flexDirection: 'column', paddingTop:20}}>
<Text>Pass UserName prop to createBottomTabNavigator</Text>
<Button title='Login!' onPress={this._navToMain}/>
</View>
)
}
}

Open Drawer by clicking in header of containing StackNavigator

This is the component which contains my Drawer
export default class StackInView extends React.Component {
render() {
const Stack = StackNavigator({
DrawerStack: { screen: DrawerInView }
}, {
headerMode: 'float',
});
return (
<View style={{ flex: 1 }}>
<Stack />
</View>
);
}
}
The following is where I define my button. I want to define the button in navigationOptions of the screen, because the button should only appear on the screen with the drawer. But clicking the button doesn't work can you help me pls?
... imports ...
export default class DrawerInView extends React.Component {
static navigationOptions = {
title: "Yeah?",
headerRight: <Button title="Menu" onPress={() => {NavigationActions.navigate("DrawerOpen")}}/>
}
constructor(props) {
super(props);
}
render() {
const Drawer = DrawerNavigator({
"one": {
screen: () => {
return (<TabsInView select="something" />)
},
},
"two": {
screen: () => {
return (<TabsInView select="something else" />)
},
}
})
return (
<View style={{ flex: 1 }}>
<Drawer />
</View>
);
}
}
You can open DrawerNavigation on button click like this.
<Button title="Menu" onPress ={ ( ) => this.props.navigation.openDrawer()} />
Don't put Stack into View. It's hard to understand and you break all props.
And the reason it doesn't work is that navigationOptions in second code is not for the drawer but for the StackNavigator in the first code. So it can't execute drawer's navigation.navigate("DrawerOpen") because it's StackNavigator's.
And I highly recommend you to change your app's hierarchy. It's really hard that child Drawer passes its navigation to parent Stack's right button.
Then, it would look like this.
const MyStack = StackNavigator({
Tabs:{ screen: MyTabs, navigationOptions:(props) => ({
headerRight:
<TouchableOpacity onPress={() => {props.screenProps.myDrawerNavigation.navigate('DrawerOpen')}}>
<Text>Open Drawer</Text>
</TouchableOpacity>
})}
}
, {navigationOptions:commonNavigationOptions})
const MyDrawer = DrawerNavigator({
stack1: {
screen: ({navigation}) => <MyStack screenProps={{myDrawerNavigation:navigation}} />,
},
stack2: {
//more screen
}
})

Add hamburger button to React Native Navigation

I'm very new to React-Native so I definitely may be missing something. But all I want to do is add a hamburger type button to a settings page in the main Navigation bar. I have set up a link in the main part of that works the way I want hamburger button to work.
Screenshot
import React from 'react';
import { AppRegistry, Text, View, Button } from 'react-native';
import { StackNavigator } from 'react-navigation';
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Welcome',
headerLeft: <Button onPress={ WHAT GOES HERE?? } title= "=" />
};
render() {
const { navigate } = this.props.navigation;
return (
<Button
onPress={() => navigate('Settings')}
title="Link to Settings" />
);
}
}
class Settings extends React.Component {
static navigationOptions = {
title: 'Settings',
headerLeft: <Button title= "=" />
};
render() {
return <Text>Hello, Settings!</Text>;
}
}
const SimpleApp = StackNavigator({
Home: { screen: HomeScreen },
Settings: { screen: Settings}
});
AppRegistry.registerComponent('NavPractice', () => SimpleApp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Having this, you're very close to the solution.
static navigationOptions = {
title: 'Welcome',
headerLeft: <Button onPress={ WHAT GOES HERE?? } title= "=" />
};
A little-known fact is that navigationOptions accepts a function that returns navigation options. That function accepts some props, navigation one of them. Know this, adjust your code a little.
static navigationOptions = function(props) {
return {
title: 'Welcome',
headerLeft: <Button onPress={() => props.navigation.navigate('DrawerOpen')} title= "=" />
}
};
check this link with same issue https://github.com/react-community/react-navigation/issues/1539
check navigationOptions
navigationOptions: ({ navigation }) => ({
title: 'Schedules', // Title to appear in status bar
headerLeft: <Icon name="menu" size={35}
onPress={ () => navigation.navigate('DrawerOpen') } />
from
const SchedulesStack = StackNavigator({
Schedules: {
screen: SchedulesScreen,
navigationOptions: ({ navigation }) => ({
title: 'Schedules', // Title to appear in status bar
headerLeft: <Icon name="menu" size={35} onPress={ () => navigation.navigate('DrawerOpen') } />
})
}
});
const Homestack = StackNavigator({
Home: {
Screen: Home
navigationOptions: ({ navigation }) => ({
title: 'Home', // Title to appear in status bar
headerLeft: <Icon name="menu" size={35} onPress={ () => navigation.navigate('DrawerOpen') } />
})
}
});
const Root = DrawerNavigator({
Home: {
screen: HomeStack,
navigationOptions: {
title: 'Home' // Text shown in left menu
}
},
Schedules: {
screen: SchedulesStack,
navigationOptions: {
title: 'Schedules', // Text shown in left menu
}
}
}
})
In the above code it seems you are adding options to the sidebar and navigating to the sidebar menus.
//sidebar menu no.1
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Welcome',
headerLeft: <Button onPress={//action taken when option in the menu bar is clicked} title= "//the title of the screen where you will navigate and the sidebar menu lable" />
};
render() {
const { navigate } = this.props.navigation;
return (
<Button
onPress={() => navigate('Settings')}
title="Link to Settings" />
);
}
}
In this way you can create as many drawer options as you can.. now how to combine drawer options:
//react navigation provides you with DrawerNavigator API
const MyApp = DrawerNavigator({
Home: {
screenA: HomeScreen ,
},
Settings: {
screen: MySettingScreens,
},
});
The drawer also comes with a prop that is screenProps={/* this prop will get passed to the screen components and nav options as props.screenProps */}, like this :
<MyApp
screenProps={/* this prop will get passed to the screen components and nav options as props.screenProps */}
/>
Following are the props that react navigator provide to open/close drawer.
this.props.navigation.navigate('DrawerOpen'); // open drawer
this.props.navigation.navigate('DrawerClose'); // close drawer
You can also set the drawer style according to you, like this:
drawerWidth - Width of the drawer
drawerPosition - Options are left or right. Default is left position.
contentComponent - By default there is no scrollview available in the drawer. In order to add scrollview in the drawer you need to add contentComponent in the configuration.
contentOptions - As the name suggest these are used to give color to the active and inactive drawer items (label).
Cheers :)