0
votes

I want to redirect to home page after i clicked on a button in login page..But when i clicked the button in address bar ,home page's path is shown( it redirects to the home page)..but it doesn't render the component relevant to that path.It still shows the login page with home page address.So,i have to refresh the page to render the home page.what is wrong here???

In my login page...this is the function i used for the button onClick..

gotopage()
  {
        this.props.history.push('/home')
   }

In my index,js page..

import React from "react";
import { render } from "react-dom";
import {BrowserRouter as Router,Route,Redirect ,browserHistory} from "react-router-dom"; 
import { Firstpage } from "./Firstpage";
import { Login } from "./Login";
import { Home } from "./Home";
import createBrowserHistory from 'history/createBrowserHistory'
const history=createBrowserHistory();


    class App extends React.Component {
    render(){
    return(
    <Router history={browserHistory}>
         <div>
        <switch>
        <Route path="/"   component={Firstpage} exact> </Route>
        <Route path="/home"   component={Home}> </Route>
        <Route path="/login"  render={(props) => <Login {...props} history= 
         {history} } />}> </Route>
         </switch>
         </div>
     </Router>
     );
   }
 }
1
Pls add the route specificationsRohith Murali
add the router config.Shubham Gupta
and add the component which should navigate to home pageAlex
react router version you are usingShubham Gupta
version is 4.3.1Sandz

1 Answers

0
votes

There are a couple of things I would suggest. Since you are using React router 4.x BrowserRouter has no history prop as per documentation remove that. Update your code to following and see if it works.

Change switch to Switch and I can't see it being imported from react-router. use withRouter from react-router in your Login component.

export default withRouter(Login)

Update the main route config as followed.

     <Router history={browserHistory}>
        <Switch>
            <Route path="/"   component={Firstpage} exact> </Route>
            <Route path="/home"   component={Home}> </Route>
            <Route path="/login"  render={(props) => <Login {...props}/>}> </Route>
        </Switch>
     </Router>

Read more about withRouter, BrowserRouter here https://reacttraining.com/react-router/web/api/BrowserRouter.

On more details take a look at the following post https://medium.com/@AkyunaAkish/understanding-react-router-4-df73a66d96c4