2

I want to redirect to home page after successful login.I searched throughly but didn't find the solution to this. Thanks in advance

//imported react-router
import { Redirect } from 'react-router';

//main route file
<Router>
  <div>
    <Route exact path = "/" component={ App } />
    <Route path = "/home" component={ Homepage } />
  </div>
</Router>

//redirect after ajax success
$.ajax({
    type: 'POST',
    url: '/login_participant',
    data: data,
    dataType:'json',
    success:function(data) {
         console.log(data);

         //redirecting home after login successfully
         <Redirect to ="/home" />
    },
    error:function(err) {
         console.log(err);
    }
})
1
  • you are using redirect wrongly. its a jsx tag. it needs to be in the render function. Also stop using jquery ajax and react. its a bad practice. use either axios or fetch function for your ajax calls. this is how you use the redirect jsx tag. stackoverflow.com/questions/43230194/… Commented Nov 16, 2017 at 11:14

1 Answer 1

0

<Redirect /> is a simple component, that takes some props and do something with that. It has contract with other components provided by react-router, so it has to know what is the context.

If you want to redirect after successful login, you either have to use react-router-redux (push action) or to keep state flag isUserLoggedIn or sth like that to provide data to your components. Both solution requires using redux/flux or other state container.

If you don't want to use redux/flux, maybe just replace window location? (pathname).

It's all from my side, maybe others have better solution.

Sign up to request clarification or add additional context in comments.

7 Comments

I am new to react. please provide a perpect solution to this
If you're not using redux currently it is major change in your project. I can provide some solution, but I need to look at this a little bit wider. Are you able to provide some sample of your project? If you don't want to do this, I recommend to redirect user with standard javascript API that I mentioned - to replace window location. It is 1 line to change, no major changes. Just Replace your <Redirect /> with window.location = 'your_successful_login_location, or if it is in same origin, maybe just window.location.pathname = 'your_pathaneme';
window.location not working for me
Try window.location.pathname = '/home'; (in your case)
this is also not working
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.