How do I conditionally redirect with react-router?React Router Redirect ConditionalLoop inside React JSXReact-router Async redirect in willTransitionToProgrammatically navigate using react routerReact + React-Router: Re-render Navbar component when children component is replaced on redirectAuth based redirecting with react-routerReact router private routes / redirect not workingReactJS MobX and react-router v4 issue with url historyReact-router how to redirect to an Express GETConfusing behavior of Redirect in React-router-domHow to make a <Route> Component observe loggedIn status state from store?

Can we show a sum of symmetrical cosine values is zero by using roots of unity?

Why sampling a periodic signal doesn't yield a periodic discrete signal?

Gravitational Force Between Numbers

The Maltese Falcon

Are runways booked by airlines to land their planes?

Co-author wants to put their current funding source in the acknowledgements section because they edited the paper

Looping over charts and names simultaneously

How to let other coworkers know that I don't share my coworker's political views?

Is it legal to have an abortion in another state or abroad?

Is there an idiom that means that you are in a very strong negotiation position in a negotiation?

Time complexity of an algorithm: Is it important to state the base of the logarithm?

How to keep consistency across the application architecture as a team grows?

Why is this integration method not valid?

I want to know what "marumaru" means

USPS Back Room - Trespassing?

Is there any chance a man can get the death penalty for causing a miscarriage?

A burglar's sunglasses, a lady's odyssey

Why is unzipped directory exactly 4.0k (much smaller than zipped file)?

What is the recommended procedure to land a taildragger in a crosswind?

How to determine if a hyphen (-) exists inside a column

Why does the Starter Set wizard have six spells in their spellbook?

Can a ring of spell storing and access to Find spells produce an endless menagerie?

Freedom of Speech and Assembly in China

What would prevent living skin from being a good conductor for magic?



How do I conditionally redirect with react-router?


React Router Redirect ConditionalLoop inside React JSXReact-router Async redirect in willTransitionToProgrammatically navigate using react routerReact + React-Router: Re-render Navbar component when children component is replaced on redirectAuth based redirecting with react-routerReact router private routes / redirect not workingReactJS MobX and react-router v4 issue with url historyReact-router how to redirect to an Express GETConfusing behavior of Redirect in React-router-domHow to make a <Route> Component observe loggedIn status state from store?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm trying to redirect from a login screen to a home screen. How do I implement a conditional redirect correctly in ReactJS?



I have tried to redirect to components based on the state. this.state.loggedIn returns true or false as I expect it to do.



import React from 'react';
import Router,
Route,
Link,
Redirect
from "react-router-dom";
import history from '../history';
import LoginView from './LoginView';
import SearchPanel from './SearchPanel';
import "./style.css";


class App extends React.Component
state = token: '', groupId: '', hostName: '', loggedIn: false;

getLoginData = async (props) =>
this.setState(loggedIn: true);
console.log(this.state.loggedIn);
this.setState( token: props.token, groupId: props.token.groupId.data, hostName: props.token.hostName );
;

render()
return (
<Router history=history>
<div className="background">
<Route
exact
path="/"
render=() =>
!this.state.loggedIn ? (
history.replace("/login")
) : (
history.replace("/home")
)

/>
<Route
path="/login"
component=() => <LoginView onLogin=this.getLoginData />
/>
<Route
path="/home"
component=() => (
<SearchPanel
token=this.state.token
groupId=this.state.groupId
hostName=this.state.hostName
/>
)
/>
</div>
</Router>


)



export default App;


I expect to be redirected to /home, but it stays on /login










share|improve this question



















  • 1





    Check out this answer stackoverflow.com/questions/45805930/…

    – Matic
    Mar 23 at 23:36

















0















I'm trying to redirect from a login screen to a home screen. How do I implement a conditional redirect correctly in ReactJS?



I have tried to redirect to components based on the state. this.state.loggedIn returns true or false as I expect it to do.



import React from 'react';
import Router,
Route,
Link,
Redirect
from "react-router-dom";
import history from '../history';
import LoginView from './LoginView';
import SearchPanel from './SearchPanel';
import "./style.css";


class App extends React.Component
state = token: '', groupId: '', hostName: '', loggedIn: false;

getLoginData = async (props) =>
this.setState(loggedIn: true);
console.log(this.state.loggedIn);
this.setState( token: props.token, groupId: props.token.groupId.data, hostName: props.token.hostName );
;

render()
return (
<Router history=history>
<div className="background">
<Route
exact
path="/"
render=() =>
!this.state.loggedIn ? (
history.replace("/login")
) : (
history.replace("/home")
)

/>
<Route
path="/login"
component=() => <LoginView onLogin=this.getLoginData />
/>
<Route
path="/home"
component=() => (
<SearchPanel
token=this.state.token
groupId=this.state.groupId
hostName=this.state.hostName
/>
)
/>
</div>
</Router>


)



export default App;


I expect to be redirected to /home, but it stays on /login










share|improve this question



















  • 1





    Check out this answer stackoverflow.com/questions/45805930/…

    – Matic
    Mar 23 at 23:36













0












0








0








I'm trying to redirect from a login screen to a home screen. How do I implement a conditional redirect correctly in ReactJS?



I have tried to redirect to components based on the state. this.state.loggedIn returns true or false as I expect it to do.



import React from 'react';
import Router,
Route,
Link,
Redirect
from "react-router-dom";
import history from '../history';
import LoginView from './LoginView';
import SearchPanel from './SearchPanel';
import "./style.css";


class App extends React.Component
state = token: '', groupId: '', hostName: '', loggedIn: false;

getLoginData = async (props) =>
this.setState(loggedIn: true);
console.log(this.state.loggedIn);
this.setState( token: props.token, groupId: props.token.groupId.data, hostName: props.token.hostName );
;

render()
return (
<Router history=history>
<div className="background">
<Route
exact
path="/"
render=() =>
!this.state.loggedIn ? (
history.replace("/login")
) : (
history.replace("/home")
)

/>
<Route
path="/login"
component=() => <LoginView onLogin=this.getLoginData />
/>
<Route
path="/home"
component=() => (
<SearchPanel
token=this.state.token
groupId=this.state.groupId
hostName=this.state.hostName
/>
)
/>
</div>
</Router>


)



export default App;


I expect to be redirected to /home, but it stays on /login










share|improve this question
















I'm trying to redirect from a login screen to a home screen. How do I implement a conditional redirect correctly in ReactJS?



I have tried to redirect to components based on the state. this.state.loggedIn returns true or false as I expect it to do.



import React from 'react';
import Router,
Route,
Link,
Redirect
from "react-router-dom";
import history from '../history';
import LoginView from './LoginView';
import SearchPanel from './SearchPanel';
import "./style.css";


class App extends React.Component
state = token: '', groupId: '', hostName: '', loggedIn: false;

getLoginData = async (props) =>
this.setState(loggedIn: true);
console.log(this.state.loggedIn);
this.setState( token: props.token, groupId: props.token.groupId.data, hostName: props.token.hostName );
;

render()
return (
<Router history=history>
<div className="background">
<Route
exact
path="/"
render=() =>
!this.state.loggedIn ? (
history.replace("/login")
) : (
history.replace("/home")
)

/>
<Route
path="/login"
component=() => <LoginView onLogin=this.getLoginData />
/>
<Route
path="/home"
component=() => (
<SearchPanel
token=this.state.token
groupId=this.state.groupId
hostName=this.state.hostName
/>
)
/>
</div>
</Router>


)



export default App;


I expect to be redirected to /home, but it stays on /login







reactjs react-router






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 11:44







Luc

















asked Mar 23 at 23:35









LucLuc

32




32







  • 1





    Check out this answer stackoverflow.com/questions/45805930/…

    – Matic
    Mar 23 at 23:36












  • 1





    Check out this answer stackoverflow.com/questions/45805930/…

    – Matic
    Mar 23 at 23:36







1




1





Check out this answer stackoverflow.com/questions/45805930/…

– Matic
Mar 23 at 23:36





Check out this answer stackoverflow.com/questions/45805930/…

– Matic
Mar 23 at 23:36












1 Answer
1






active

oldest

votes


















1














<Route/> has an history object, use that
this.props.history.replace("/home")



Using .replace() assures that the user can't navigate back to login again. Otherwise use .push().






share|improve this answer


















  • 1





    I passed a history prop to my router and used .push and/or .replace for both cases. still the same result

    – Luc
    Mar 24 at 0:03











  • Please, Show your modified code.

    – its4zahoor
    Mar 24 at 3:07











  • Check this it works, it's your code. codesandbox.io/s/olnyzr826q . change loggedIn state manually and go to "/" from address bar and refresh.

    – its4zahoor
    Mar 24 at 7:21






  • 1





    That does work indeed, but it doesn't automatically redirect the user when the state is changed.

    – Luc
    Mar 24 at 11:32






  • 1





    I fixed it! I had to redirect it to "/" after I changed the state. Otherwise it would always skip the render() in the first Route and stay on "/login"

    – Luc
    Mar 24 at 12:41











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55319364%2fhow-do-i-conditionally-redirect-with-react-router%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














<Route/> has an history object, use that
this.props.history.replace("/home")



Using .replace() assures that the user can't navigate back to login again. Otherwise use .push().






share|improve this answer


















  • 1





    I passed a history prop to my router and used .push and/or .replace for both cases. still the same result

    – Luc
    Mar 24 at 0:03











  • Please, Show your modified code.

    – its4zahoor
    Mar 24 at 3:07











  • Check this it works, it's your code. codesandbox.io/s/olnyzr826q . change loggedIn state manually and go to "/" from address bar and refresh.

    – its4zahoor
    Mar 24 at 7:21






  • 1





    That does work indeed, but it doesn't automatically redirect the user when the state is changed.

    – Luc
    Mar 24 at 11:32






  • 1





    I fixed it! I had to redirect it to "/" after I changed the state. Otherwise it would always skip the render() in the first Route and stay on "/login"

    – Luc
    Mar 24 at 12:41















1














<Route/> has an history object, use that
this.props.history.replace("/home")



Using .replace() assures that the user can't navigate back to login again. Otherwise use .push().






share|improve this answer


















  • 1





    I passed a history prop to my router and used .push and/or .replace for both cases. still the same result

    – Luc
    Mar 24 at 0:03











  • Please, Show your modified code.

    – its4zahoor
    Mar 24 at 3:07











  • Check this it works, it's your code. codesandbox.io/s/olnyzr826q . change loggedIn state manually and go to "/" from address bar and refresh.

    – its4zahoor
    Mar 24 at 7:21






  • 1





    That does work indeed, but it doesn't automatically redirect the user when the state is changed.

    – Luc
    Mar 24 at 11:32






  • 1





    I fixed it! I had to redirect it to "/" after I changed the state. Otherwise it would always skip the render() in the first Route and stay on "/login"

    – Luc
    Mar 24 at 12:41













1












1








1







<Route/> has an history object, use that
this.props.history.replace("/home")



Using .replace() assures that the user can't navigate back to login again. Otherwise use .push().






share|improve this answer













<Route/> has an history object, use that
this.props.history.replace("/home")



Using .replace() assures that the user can't navigate back to login again. Otherwise use .push().







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 23 at 23:43









its4zahoorits4zahoor

486413




486413







  • 1





    I passed a history prop to my router and used .push and/or .replace for both cases. still the same result

    – Luc
    Mar 24 at 0:03











  • Please, Show your modified code.

    – its4zahoor
    Mar 24 at 3:07











  • Check this it works, it's your code. codesandbox.io/s/olnyzr826q . change loggedIn state manually and go to "/" from address bar and refresh.

    – its4zahoor
    Mar 24 at 7:21






  • 1





    That does work indeed, but it doesn't automatically redirect the user when the state is changed.

    – Luc
    Mar 24 at 11:32






  • 1





    I fixed it! I had to redirect it to "/" after I changed the state. Otherwise it would always skip the render() in the first Route and stay on "/login"

    – Luc
    Mar 24 at 12:41












  • 1





    I passed a history prop to my router and used .push and/or .replace for both cases. still the same result

    – Luc
    Mar 24 at 0:03











  • Please, Show your modified code.

    – its4zahoor
    Mar 24 at 3:07











  • Check this it works, it's your code. codesandbox.io/s/olnyzr826q . change loggedIn state manually and go to "/" from address bar and refresh.

    – its4zahoor
    Mar 24 at 7:21






  • 1





    That does work indeed, but it doesn't automatically redirect the user when the state is changed.

    – Luc
    Mar 24 at 11:32






  • 1





    I fixed it! I had to redirect it to "/" after I changed the state. Otherwise it would always skip the render() in the first Route and stay on "/login"

    – Luc
    Mar 24 at 12:41







1




1





I passed a history prop to my router and used .push and/or .replace for both cases. still the same result

– Luc
Mar 24 at 0:03





I passed a history prop to my router and used .push and/or .replace for both cases. still the same result

– Luc
Mar 24 at 0:03













Please, Show your modified code.

– its4zahoor
Mar 24 at 3:07





Please, Show your modified code.

– its4zahoor
Mar 24 at 3:07













Check this it works, it's your code. codesandbox.io/s/olnyzr826q . change loggedIn state manually and go to "/" from address bar and refresh.

– its4zahoor
Mar 24 at 7:21





Check this it works, it's your code. codesandbox.io/s/olnyzr826q . change loggedIn state manually and go to "/" from address bar and refresh.

– its4zahoor
Mar 24 at 7:21




1




1





That does work indeed, but it doesn't automatically redirect the user when the state is changed.

– Luc
Mar 24 at 11:32





That does work indeed, but it doesn't automatically redirect the user when the state is changed.

– Luc
Mar 24 at 11:32




1




1





I fixed it! I had to redirect it to "/" after I changed the state. Otherwise it would always skip the render() in the first Route and stay on "/login"

– Luc
Mar 24 at 12:41





I fixed it! I had to redirect it to "/" after I changed the state. Otherwise it would always skip the render() in the first Route and stay on "/login"

– Luc
Mar 24 at 12:41



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55319364%2fhow-do-i-conditionally-redirect-with-react-router%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현