I have a page that validates a user and redirects them to a login page if validation is successful. However, the using redirect
the URL changes but the new page for Login
is not rendered. How can I get the new page to render?
App.js
var child;
render() {
if (this.state.toLogin && !this.state.mounted) {
<Route exact path="/Login" component={Login} />;
<Route exact strict path="/" render={({location}) => {
if (location.pathname === window.location.pathname) {
return <Redirect to="/Login"/>;
}
return null;
}}
return(
<div className="App">
<ReactCSSTransitionGroup
transitionName="remove"
transitionEnterTimeout={100}
transitionLeaveTimeout={100}>
{child}
</ReactCSSTransitionGroup>
</div>
);
}
Index.js
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
EDIT: Made changes as per answers but now the URL is not changing and the page is not rendering
Method 2: Adding a new state with pushState() Method: The pushState() method is used to add a new history entry with the properties passed as parameters. This will change the current URL to the new state given without reloading the page.
To redirect to another page on button click in React: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function, passing it the path - navigate('/about') . The navigate() function lets us navigate programmatically.
The Redirect component was usually used in previous versions of the react-router-dom package to quickly do redirects by simply importing the component from react-router-dom and then making use of the component by providing the to prop, passing the page you desire to redirect to.
React Router has an higher-order component called withRouter with which we can pass in the React Router's history, location, and match objects to our React components as props. To use withRouter , you should wrap your App component inside withRouter() as a parameter.
if you are using react-router-dom
wrap your component export in withRouter
provided by react-router-dom
.
and all component usage should be returned from render. then only react knows what to render.
import React from 'react'
import { withRouter, Redirect } from 'react-router-dom';
class App extends React.Component {
render() {
if (this.state.toLogin && !this.state.mounted) {
return (
<React.Fragment>
<Route exact path="/Login" component={Login} />
<Route exact strict path="/" render={({location}) => {
if (location.pathname === window.location.pathname) {
return <Redirect to="/Login"/>;
}
return null;
}} />
</React.Fragment>
);
}
return (
<div className="App">
<ReactCSSTransitionGroup
transitionName="remove"
transitionEnterTimeout={100}
transitionLeaveTimeout={100}>
{child}
</ReactCSSTransitionGroup>
</div>
)}
}
export default withRouter(App)
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