use navigate method anywhere - reactjs

I have a component that not assign in StackNavigator. However I still want to use navigate method from react-navigation. Is that possible ?
For example:
manage.js
export const mainStack = StackNavigator({
Home: { screen: HomeScreen},
Content: { screen: ContentScreen },
});
OtherContent.js
class OtherContent extends React.Component {
constructor(props) {
super(props);
}
_MoveToScreen = () =>{
//try to open ContentScreen from here
const { navigate } = this.props.navigation;
navigate('ContentScreen');
}
}
I want to use navigate in OtherContent component. How can I pass the navigation props to the component.

Use redux and put it in the state, then u can call it from there i think

You can pass navigation from parent as props or use withNavigation Higher Order Component by react-navigation
Example 1:
<OtherContent navigation={this.props.navigation} />
Example 2:
import React from 'react';
import { withNavigation } from 'react-navigation';
class OtherContent extends React.Component {
constructor(props) {
super(props);
}
_MoveToScreen = () =>{
//try to open ContentScreen from here
const { navigate } = this.props.navigation;
navigate('ContentScreen');
}
// ...
}
const OtherContentWithNavigation = withNavigation(OtherContent);
;

Related

How can I obtain class props from url and store in react-redux

so I am trying to pass params using route to a react component and also at the same time use Component class props. Here is what am doing
import { loadSchemes, } from '../../actions/schemes;
export class Schemes extends Component {
constructor(props) {
super(props);
const { match: { params } } = this.props;
this.state = {
client_id: params.pk,
}
}
componentDidMount() {
this.props.loadSchemes();
}
render(){
return(
<div>
{this.props.schemes_list.map((scheme,index)=><p key={index}>{scheme}</p>)}
</div>
)
}
}
const mapStateToProps = (state) => ({
schemes_list: state.schemes,
});
export default connect(mapStateToProps,{ loadSchemes,})(Schemes);
And I have a url to this component as
<Route path="/client/:pk/schemes" component={Schemes}/>
The problem is I get an error this.props.schemes_list is undefined and this.props.loadSchemes is undefined
please help am using react-redux
Obviousely in component from where you call Scheme, you import { Schemes }, an unconnected component, instead of Schemes - default connected component. Please check it.

react-navigation navigate is not a function error. - Class component

I'm using react native class component and I'm using react-navigation to route in the app. the guide is mostly for the functional component and I'm trying to implement it with class components. but when i trying to get it from reactnavigation it always throws me error that navigation is not a function or undefined. Im sorry if this is an already asked question as I'm really new to this react native.
class component
import React from 'react';
import { useNavigation } from '#react-navigation/native';
import { Button, Divider, Layout, TopNavigation ,Card,Text} from '#ui-kitten/components';
class HomeScreen extends React.Component {
navigateDetails(navigation) {
debugger
navigation('Details');
};
constructor(props) {
super(props);
console.log(this.props);
this.state = { hover: false };
}
render() {
const navigation = this.props;
return(
<Button onPress={this.navigateDetails}>OPEN DETAILS</Button>
);
}
}
export default function (props) {
const navigation = useNavigation();
return <HomeScreen {...props} navigation={navigation} />;
}
First, you have to make sure navigation prop is exist in your class component (As looking in your code its already exist) and the second thing is this.props.navigation is an object, not a function which holds different function like navigate, push etc so you have to execute these functions, here are some changes I did in your code and I hope this will work for you.
class HomeScreen extends React.Component {
constructor(props) {
super(props);
console.log(this.props);
this.state = { hover: false };
}
navigateDetails() {
this.props.navigation.navigate('Details');
};
render() {
const navigation = this.props;
return(
<Button onPress={()=>this.navigateDetails()}>OPEN DETAILS</Button>
);
}
}
export default function (props) {
const navigation = useNavigation();
return <HomeScreen {...props} navigation={navigation} />;
}
Seems I have to pass that navigation to the function as a variable in order to work. so I have changed the function as bellow to pass the navigation to the
function and also changed this.navigateDetails(navigation) to
()=>this.navigateDetails(navigation)
also, I destructed the navigation like const {navigation} = this.props;
full code line
onPress={()=>this.navigateDetails(navigation)}

Getting data from one class to make it the title of stackNavigator tab?

import { createStackNavigator } from "react-navigation";
import React, { Component } from "react";
class Navigator extends React.Component {
render() {
const TitleNameParam = navigation.getParam('TitleNameParam');
var TitleNameString = JSON.stringify(TitleNameParam);
var TitleNameObject = JSON.parse(TitleNameString);
}
}
const AppNavigator = createStackNavigator({
Launching: {
screen: LaunchingScreen,
navigationOptions: {
title: "Launching Soon",
headerTitleAllowFontScaling: true,
headerBackTitle: "Back"
}
},
InfoScreen: {
screen: InfoScreen,
navigationOptions: {
title: Navigator.TitleNameParam,
}
}
});
export default AppNavigator;
So what I want to do is get data (that's from an API) from one class to the stack navigator class so I can replace the title to whatever the data is. What I have right now is class Navigator getting data ( from TitleNameParam ) that makes the data into a string in which the navigator attempts to get it in the InfoScreen tab, but nothing shows up.
Use navigationOptions on the InfoScreen component:
class InfoScreen extends React.Component {
// Set the navigation options for `react-navigation`
static navigationOptions = ({navigation}) => {
return {
headerTitle: navigation.getParam('TitleNameParam');
}
}
…
}
When you navigate to this route use:
this.props.navigation.navigate('InfoScreen', {TitleNameParam: yourComputedTitleName})
Please let me know if this is correct.

undefined is not an object (evaluating 'this.props.navigation') react navigation

I'm using React Stack Navigator in React Native App. I have a problem with the navigation props.
Here is my component where I call my navigate method.
class CommandsList extends React.Component {
constructor(props){
super(props);
}
addCommand(){
this.props.navigation.navigate("CreateCommand");
}
render() {
return (
<SafeAreaView style={{flex:1}}>
<MyList itemsUrl="http://localhost:9000/commands"/>
<Button title="Ajouter" onPress={this.addCommand}></Button>
</SafeAreaView>
);
}
}
export default StackNavigator({
CommandsList : {
screen : CommandsList,
},
});
And my App.js
const RootStack = StackNavigator(
{
CommandsList: {
screen: CommandsList,
},
CreateCommand: {
screen: CreateCommand,
}
},
{
initialRouteName: 'CommandsList'
}
);
export default class App extends React.Component {
render() {
return <RootStack/>;
}
}
I don't understand why I have an error on navigate methods. :/
You need to bind your reference either using bind in the constructor or by using the fat arrow function to reference this to the context
addCommand = () => {
this.props.navigation.navigate("CreateCommand");
}
or
constructor() {
super()
this.addCommand = this.addCommand.bind(this);
}
Also you may check this article

How to get current navigation state

I am using React Navigation's Tab Navigator from https://reactnavigation.org/docs/navigators/tab, when I switch between the Tab Screens I don't get any navigation state in this.props.navigation.
Tab Navigator:
import React, { Component } from 'react';
import { View, Text, Image} from 'react-native';
import DashboardTabScreen from 'FinanceBakerZ/src/components/dashboard/DashboardTabScreen';
import { TabNavigator } from 'react-navigation';
render() {
console.log(this.props.navigation);
return (
<View>
<DashboardTabNavigator />
</View>
);
}
const DashboardTabNavigator = TabNavigator({
TODAY: {
screen: DashboardTabScreen
},
THISWEEK: {
screen: DashboardTabScreen
}
});
DASHBOARD SCREEN:
import React, { Component } from 'react';
import { View, Text} from 'react-native';
export default class DashboardTabScreen extends Component {
constructor(props) {
super(props);
this.state = {};
console.log('props', props);
}
render() {
console.log('props', this.props);
return (
<View style={{flex: 1}}>
<Text>Checking!</Text>
</View>
);
}
}
I get props at Dashboard Screen when it renders the component first but I don't get props when I switch the tabs.
I need to get the current Screen name i.e TODAY or THISWEEK.
Your problem is about "Screen Tracking", react-navigation has an officially guide for this. you can use onNavigationStateChange to track the screen by using built-in navigation container or write a Redux middleware to track the screen if you want to integrate with Redux. More detail can be found at the officially guide: Screen-Tracking. Below is a sample code from the guide by using onNavigationStateChange:
import { GoogleAnalyticsTracker } from 'react-native-google-analytics-bridge';
const tracker = new GoogleAnalyticsTracker(GA_TRACKING_ID);
// gets the current screen from navigation state
function getCurrentRouteName(navigationState) {
if (!navigationState) {
return null;
}
const route = navigationState.routes[navigationState.index];
// dive into nested navigators
if (route.routes) {
return getCurrentRouteName(route);
}
return route.routeName;
}
const AppNavigator = StackNavigator(AppRouteConfigs);
export default () => (
<AppNavigator
onNavigationStateChange={(prevState, currentState) => {
const currentScreen = getCurrentRouteName(currentState);
const prevScreen = getCurrentRouteName(prevState);
if (prevScreen !== currentScreen) {
// the line below uses the Google Analytics tracker
// change the tracker here to use other Mobile analytics SDK.
tracker.trackScreenView(currentScreen);
}
}}
/>
);
Check all properties first, like
<Text>{JSON.stringify(this.props, null, 2)}</Text>
Above json array will show you current state of navigation under routeName index i.e.
this.props.navigation.state.routeName
Have you tried to define navigationOptions in your route object?
const DashboardTabNavigator = TabNavigator({
TODAY: {
screen: DashboardTabScreen
navigationOptions: {
title: 'TODAY',
},
},
})
You can also set navigationOptions to a callback that will be invoked with the navigation object.
const DashboardTabNavigator = TabNavigator({
TODAY: {
screen: DashboardTabScreen
navigationOptions: ({ navigation }) => ({
title: 'TODAY',
navigationState: navigation.state,
})
},
})
Read more about navigationOptions https://reactnavigation.org/docs/navigators/
Answer as of React Navigation v6
Depending on whether you want to trigger re-renders on value changes:
const state = navigation.getState();
or
const state = useNavigationState(state => state);
Reference:
https://reactnavigation.org/docs/use-navigation-state#how-is-usenavigationstate-different-from-navigationgetstate

Resources