Reactjs Redirecting to Another Page

How to do a redirect to another route with react-router?

For the simple answer, you can use Link component from react-router, instead of button. There is ways to change the route in JS, but seems you don't need that here.

<span className="input-group-btn">
<Link to="/login" />Click to login</Link>
</span>

To do it programmatically in 1.0.x, you do like this, inside your clickHandler function:

this.history.pushState(null, 'login');

Taken from upgrade doc here

You should have this.history placed on your route handler component by react-router. If it child component beneath that mentioned in routes definition, you may need pass that down further

ReactJS redirecting to another page on successful statement not working

Issue

  1. You can't return JSX from an asynchronous callback and expect it to be rendered and take effect. The Redirect must be rendered in the return of the component.

  2. The reason using the history object wasn't working is because the handleSubmit handler is outside the router providing any routing context to navigate against.

Solution

  1. Use the history object to issue an imperative redirect.
  2. Move the HashRouter to wrap App and provide a routing context for the history object. In fact, you should have only one router wrapping your app to provide the routing context, so remove all other extraneous routers you may have in your app.

Example:

index.js

import { HashRouter as Router } from 'react-router-dom';

...

ReactDOM.render(
<React.StrictMode>
<Router>
<App/>
</Router>
</React.StrictMode>,
document.getElementById('root')
);

CustomerHomePage

handleSubmit() {
const usernameInput = document.getElementById("customerLoginUsername");
const passwordInput = document.getElementById("customerLoginPassword");

if (usernameInput.value !== "customer" || passwordInput.value !== "customer") {
// alert("Wrong username or password!");
} else {
this.props.history.replace('/customerhomepage');
}
}

Route/Redirect to another page in new tab using useNavigate

react-router isn't supposed to help preserve state when opening things in a new tab. In fact, fundamentally, react isn't supposed to help do this.

I'd approach this in two ways:

  • If the data is simple enough, pass it as a query or path param using windows.open(window.open("http://link?key="+ value +"&key2="+ value2 ..."); )
  • Look into other state management methods like localstorage or something else


Related Topics



Leave a reply



Submit