Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking button to another page

I currently have a button

class Button extends Component{
    render(){
        return(
            <View>
                onPress= #I need this to return the second page of my app
                <Text style={styles.buttonText}>Next Page</Text>
            </View>
        )
    }
}

What should I do to link this button to the second page of my app? Assuming I have already imported the page.

import SecondPage from './SecondPage'
like image 809
iamacat Avatar asked Jun 06 '17 10:06

iamacat


3 Answers

use <Link> from react-router

<Link to ='/href' ></Link>
like image 26
Yash Sharma Avatar answered Oct 14 '22 00:10

Yash Sharma


There are 2 ways you can achieve this. Details below

Option 1: If you are using react router, you could use Link to redirect users to the second page.

Declare a route in your router config to go to the second page and use . More details here http://knowbody.github.io/react-router-docs/api/Link.html

Option 2: If you are not using react router and just redirecting, use the onClick on the button to redirect to a new URL. E.g. React: How to navigate via clickHandlers?

Note- Option 2 is a dirty way of navigating from one page to other. A sophisticated way will be to use react-router. You will need it when your app grows big and there are many redirects happening on the page.

Hope that helps!

like image 42
Rohan Rayarikar Avatar answered Oct 14 '22 01:10

Rohan Rayarikar


Below example can fix all your issues :

  • React Router Navigation
  • Browser Refresh Issue.
  • Browser Back Button Issue.

Please make sure you have installed react-router-dom

If not installed. Use this command to install npm i react-router-dom

index.js

   import React from "react";
   import ReactDOM from "react-dom";
   import { BrowserRouter, Route, Switch } from "react-router-dom";

   import Page1 from "./Page1";
   import Page2 from "./Page2";

    const rootElement = document.getElementById("root");
    ReactDOM.render(
      <BrowserRouter>
       <Switch>
        <Route exact path="/" component={Page1} />
        <Route path="/page2" component={Page2} />
      </Switch>
      </BrowserRouter>,
      rootElement
    );

Page1.js

   import React from "react";
   import {Link } from "react-router-dom";

    function Page1() {

        return (
          <div>
            <p>
              This is the first page.
              <br />
              Click on the button below.
            </p>
            <Link to="/page2"><button>
              Go to Page 2 
            </button>
            </Link>
          </div>
        );

    }

    export default Page1;

Page2.js

   import React from "react";

   function Page2() {

        return (
          <div>
            <p>This is the second page.</p>
          </div>
        );

    }

    export default Page2;
like image 191
Maheshvirus Avatar answered Oct 14 '22 02:10

Maheshvirus