John Rogerson
John Rogerson

Reputation: 1183

Conditional Redirect Using React Router

I have a favorites button, for which if a non-logged user clicks, they should be redirected to the login page.

This button looks like this:

                <Button
                  onClick={() => addFavorite(card, props.loggedUser)}
                  color={
                    favorites.includes(card.id) ? "google plus" : "twitter"
                  }
                  icon={
                    favorites.includes(card.id) ? "heart" : "heart outline"
                  }
                />

I've tried several ways to create a conditional to redirect the user, but I'm having some issues.

I first tried this:

onClick={() => typeof props.loggedUser.id === "undefined" ? <Redirect to="/login" /> : addFavorite(card, props.loggedUser)}

this is what my loggedUser state looks like:

{token: undefined, firstName: undefined, id: undefined, favorites: undefined, username: undefined}

i believe this is correctly catching the first condition, as the addFavorite function isn't running, but it is not redirecting to the login page.

I've also experimented with props.push history, but I'm using redux, and when i tried to wrap my main App with withRouter, it was causing issues. Not sure if I was doing it incorrectly, but I also was concerned about the other components having correct access to props. I'm probably wrong on this, but either way, if there is a best way to accomplish this, i'm all ears. Thanks.

Upvotes: 0

Views: 767

Answers (1)

Asaf Aviv
Asaf Aviv

Reputation: 11760

To manually redirect to a different route you need to use history.push(url) from the props that react-router-dom injects to the component.

If props.history is undefined you will need to wrap the component with withRouter HOC or use useHistory(hooks are available from V5.1) hook from react-router-dom

const addFavorite = (card) => {
 if(!props.loggedUser.id) {
   props.history.push('/login')
   return
 }

 // add to favorites
}

<Button onClick={() => addFavorite(card)} />

Upvotes: 2

Related Questions