Why React Doesn't Redirect to route?

I am using React And BrowserRoute Component, When I Use this way doesn't Redirect to Route For Example:

...//Code
<BrowserRouter>
  <Switch>
    <Route path="/" exact component={Home}/>
    <Route path="/profile" exact component={Profile}/>
    <Route path="/login" exact component={Login}/>
  </Switch>
</BrowserRouter>

In this Functional Components I have the following Code:

Login Component

const Login = () => {
    const loginContext = useContext(LoginContext);
    if (loginContext.isAuth) {
        return <Redirect to='/profile' />
    }
    const authUser = () => {
        loginContext.authUser();
    }

    return (
        <div className="row">
            <div className="col">
            ...
   );

Profile Component

const Profile = () => {
    const loginContext = useContext(LoginContext);
    const logOut = () => {
        loginContext.logOut()
        **return <Redirect to='/login' />**
    }
    **if (!loginContext.isAuth) {**
        return <Redirect to='/login' />
    }
    return (
        <div className="row">
            <div className="col">
            ...
    );

If I put some Logic to the logOut function when i click button like <Button ... onClick={logOut} >Log Out</Button> doesn't redirect to the Login Component But When loginContext.isAuth is false the Component works good and redirect... I used and not used Switch Component, render at Route render={...} and component={...} but doesnt' work when i want to redirect when I Click the LogOut Button, only when the loginContext.isAuth is true o false...

PSD: Sorry for my English :'(

Upvotes: 0

Views: 61

Answers (1)

DangerousDetlef
DangerousDetlef

Reputation: 381

You're using react-router-dom, correct? Routing, if you do not need a clickable link but route from code, is best done using the useHistory component exposed by react-router-dom.

For example:

import { useHistory } from 'react-router-dom';

const Profile = () => {
    const loginContext = useContext(LoginContext);
    const history = useHistory();

    const logOut = () => {
        loginContext.logOut()
        history.push({pathname: '/login'});
    }

    if (!loginContext.isAuth) {
        history.push({pathname: '/login'});
    }

    return (
        <div className="row">
            <div className="col">
            ...
    );

Upvotes: 1

Related Questions