Home > front end >  How to redirect my page to another URL in an function
How to redirect my page to another URL in an function

Time:12-03

I have a button that handles the logout for the user, but i also want that the user gets redirected to another page when logging out. (With react-router-dom) I've created a button with an on click event that executes a fuction on click, here called handleLogout, but i have problems redirecting the user to another page from the function

I have tried using: link over the button component, redirect, useNavigate but none of this worked as i wanted it to.
I have read through multiple other stackOverflow threads but none of these seem to answer my question in my Case.

I am using react version 18.0.2 and react-router-dom v6

import { Link, redirect  } from "react-router-dom"
import { Home } from "./Home"
import "./Profile.css"

export function Profile(){

    function handleLogout() {

        localStorage.removeItem("currentUser");
        
        window.location.reload();

        return redirect("/")
    }
    

    return( 
    
        <div>
            
            <button onClick={handleLogout}>Ausloggen</button>
            
        </div>
    )
    }

CodePudding user response:

To redirect the user to another page in an function using react-router-dom, you can use the useHistory hook from react-router-dom and call the push method on the history object to push a new url to the history stack and redirect the user to that page.

Here is an example of how to use the useHistory hook to redirect the user to another page when they click on the logout button:

import { useHistory } from "react-router-dom"

export function Profile() {
    const history = useHistory()

    function handleLogout() {
        localStorage.removeItem("currentUser")
        window.location.reload()
        history.push("/")
    }

    return (
        <div>
            <button onClick={handleLogout}>Ausloggen</button>
        </div>
    )
}
  • Related