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'
use <Link>
from react-router
<Link to ='/href' ></Link>
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!
Below example can fix all your issues :
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With