Shashika Virajh
Shashika Virajh

Reputation: 9477

Navigate when clicking on a button in react native

I could successfully implemented the stack and tab navigation in my project.

import React from "react";
import { StackNavigator } from "react-navigation";
import { TabNavFooter } from "./TabNavFooter";
import { SIGNIN_KEY, SIGNUP_KEY } from "../config/routeKeys";
import {
  SignupScreen,
  SigninScreen,
  MainFeedScreen,
  ProfilePageScreen,
  CommentScreen
} from "../screens";

export const Routes = StackNavigator({
  signin: { screen: SigninScreen },
  comments: { screen: CommentScreen },
  mainfeed: { screen: TabNavFooter },
  signup: { screen: SignupScreen },
  profilePage: { screen: ProfilePageScreen }
});

Now I want to navigate when I click on the comment button. My routes are in router/index.js file. How can I use this to navigate when I'm on another component? I tried this, but it didn't work.

export default class Post extends Component {
  constructor(props) {
    super(props);
  }


  commentPressedHandler = () => {
    this.props.navigation('comments');
  };

Upvotes: 1

Views: 2186

Answers (2)

micah
micah

Reputation: 1218

Here is a solution using @react-navigation/native and @react-navigation/native-stack from the react native navigation documentation. https://reactnative.dev/docs/navigation

Build React-Native route controller

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import Login from "./Login";
import Home from "./Home";

const Stack = createNativeStackNavigator();

const NavigationStack = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator screenOptions={{headerShown: false}}>
        <Stack.Screen
          name="Login"
          component={Login}
        />
        <Stack.Screen name="Home" component={CreateAccount} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default NavigationStack;

Get the navigation component injected into your view ex:

const Login = ({ navigation }) => {

Implement a function for your button that navigates to a different view.

  Login = async event => {
    console.log("Login")
    // Do Login Stuff

    // Navigate to Home View by using navigation component
    navigation.navigate("Home");
  }

Upvotes: 0

flix
flix

Reputation: 1974

you should add navigate like this this.props.navigation.navigate('Your Screen')

so try to change your code like :

commentPressedHandler = () => {
  this.props.navigation.navigate('comments');
};

instead of :

commentPressedHandler = () => {
  this.props.navigation('comments');
};

Upvotes: 1

Related Questions