DEV Community

Saleh Mubashar
Saleh Mubashar

Posted on • Edited on

useNavigate tutorial React JS

Hi guys !.

In this post we will learn how to use the useNavigate hook in React JS. useNavigate is part of React Router and has replaced useHistory, although it is similar to useHistory, but with more useful features.

useNavigate is a new hook introduced in React Router v6 and it is extremely useful and easy to use.

Uses:

  1. Go to the previous or next pages
  2. Redirect user to a specific Url

Check out my blog.


Step 1:

Install React Router as useNavigate is part of the react router dom package. Install using the following 2 commands:

Note : useNavigate is only available in React Router Dom v6

npm install history@5 react-router-dom@6

Step 2:

Import useNavigate from React Router using the following code. This line of code can be added in any react class or function (however we are using a functional component in this example).



import { useNavigate } from 'react-router';


Enter fullscreen mode Exit fullscreen mode

Step 3:

Now we will assign the useNavigate() function to a variable for ease of use. Add the following code:



let navigate = useNavigate();


Enter fullscreen mode Exit fullscreen mode

Step 4:

Now you can use the variable name anywhere to navigate to a page, previous page or next page.

Example 1:

Redirect user to another page:



function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate('/home')
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

In the above code, the navigate('/home') is used to redirect the user on button click.

Example 2:

In this example, we will see how to redirect to previous page:



function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate(-1)
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

Example 3:

In this example, we will see how to redirect user to the next page (in history)



function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate(1)
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );


Enter fullscreen mode Exit fullscreen mode

As you can see in the above two examples, -1 is used to go to the previous page while 1 is used to go to the next page.


Check Out my latest tutorial on Hubapages

Thank you all for reading this post!
If you learnt something new, you can buy me a coffee to support my work!
Cheers! πŸŽ‰

Buy Me A Coffee

Top comments (19)

Collapse
 
vishma profile image
Vishma Pratim Das

Hey,
so according to react router documentation, useNavigate() returns a method that allows us to navigate from one link to another. We don't store it inside the navigate variable. It is a hook. It is not a regular function. When we assign useNavigate() to navigate, the hook gets called and the method gets returned, which is stored inside it.

Collapse
 
nvgrae profile image
nvg-rae

Thanks for bearing with a newbie comment! I used to be able to just do this.props.history.push(/Welcome) in my class component to go to a new route from the click handler in a class component. Now I need to create an entire functional component just to use that "extremely useful and easy to use" function? Any tips on how to handle that in a class component are greatly appreciated.

Collapse
 
salehmubashar profile image
Saleh Mubashar • Edited

Hi
Ok so the problem is that you can not use this prop in class components because the children components must use react hooks to access the route context which is only possible with functional components.
Check this out: stackoverflow.com/questions/647829...

Collapse
 
nvgrae profile image
nvg-rae

Thank you for taking a look, Saleh!

Thread Thread
 
salehmubashar profile image
Saleh Mubashar • Edited

no problem :).
if you have any questions, you can always reach out to me on twitter
cheers :)

Collapse
 
fahadashiq12 profile image
Fahad Ashiq

Very Useful.

Collapse
 
bennett1412 profile image
Bennett B Madavana

Thanks for the article,
Is it okay to use a button instead of an anchor tag when you're redirecting to another page? won't it cause accessibility issues?

Collapse
 
pierre1590 profile image
Piero Sabino

Hi, I have a problem, watching a video on youtube that used history.push ('/ login? redirect = shipping'), how can I modify it using navigate, because if I use the string "navigate ('/ login? redirect = shipping') even if logged in it returns to home page and does not go to the shipping page.

Collapse
 
siyandavid profile image
siyan_david

Sorry did you figure it out im having same issue

Collapse
 
sudip_sarkar_dev profile image
Sudip Sarkar

In my case , it's not working sir , kindly help me out .

`import { json, Link, Navigate, useNavigate } from "react-router-dom";
import { useState } from "react";

import XSvg from "../../components/svgs/X";

import { MdOutlineMail } from "react-icons/md";
import { FaUser } from "react-icons/fa";
import { MdPassword } from "react-icons/md";
import { MdDriveFileRenameOutline } from "react-icons/md";
import { useMutation, useQuery } from "@tanstack/react-query";

import { toast } from "react-hot-toast";

const RegisterPage = () => {
const [formData, setFormData] = useState({
email: "",
username: "",
fullName: "",
password: "",
});
const navigate = useNavigate();

const {
    mutate: signup,
    isError,
    isPending,
    error,
} = useMutation({
    mutationFn: async ({ email, username, fullName, password }) => {
        try {
            const res = await fetch("/api/v1/auth/signup", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ fullName, username, email, password }),
            });

            const resData = await res.json();
            if (resData.error)
                throw new Error(resData.message || "Failed to create account");
        } catch (error) {
            throw error;
        }
    },
    onSuccess: () => {
        toast.success("Signed up successfully");
        navigate("/");
    },
    onError: (error) => {
        console.error(error.message);
        toast.error(error.message);
    },
});
const handleSubmit = (e) => {
    e.preventDefault();
    signup(formData);
};

const handleInputChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
};

return (
    <div className="max-w-screen-xl mx-auto flex h-screen px-10">
        <div className="flex-1 hidden lg:flex items-center  justify-center">
            <XSvg className=" lg:w-2/3 fill-white" />
        </div>
        <div className="flex-1 flex flex-col justify-center items-center">
            <form
                className="lg:w-2/3  mx-auto md:mx-20 flex gap-4 flex-col"
                onSubmit={handleSubmit}
            >
                <XSvg className="w-24 lg:hidden fill-white" />
                <h1 className="text-4xl font-extrabold text-white">Join today.</h1>

                <label className="input input-bordered rounded flex items-center gap-2">
                    <MdOutlineMail />
                    <input
                        type="email"
                        className="grow"
                        placeholder="Email"
                        name="email"
                        onChange={handleInputChange}
                        value={formData.email}
                    />
                </label>
                <div className="flex gap-4 flex-wrap">
                    <label className="input input-bordered rounded flex items-center gap-2 flex-1">
                        <FaUser />
                        <input
                            type="text"
                            className="grow "
                            placeholder="Username"
                            name="username"
                            onChange={handleInputChange}
                            value={formData.username}
                        />
                    </label>
                    <label className="input input-bordered rounded flex items-center gap-2 flex-1">
                        <MdDriveFileRenameOutline />
                        <input
                            type="text"
                            className="grow"
                            placeholder="Full Name"
                            name="fullName"
                            onChange={handleInputChange}
                            value={formData.fullName}
                        />
                    </label>
                </div>
                <label className="input input-bordered rounded flex items-center gap-2">
                    <MdPassword />
                    <input
                        type="password"
                        className="grow"
                        placeholder="Password"
                        name="password"
                        onChange={handleInputChange}
                        value={formData.password}
                    />
                </label>
                <button className="btn rounded-full btn-primary text-white">
                    {isPending ? "Loader..." : "Sign up"}
                </button>
                {isError && <p className="text-red-500">Something went wrong</p>}
            </form>
            <div className="flex flex-col lg:w-2/3 gap-2 mt-4">
                <p className="text-white text-lg">Already have an account?</p>
                <Link to="/login">
                    <button className="btn rounded-full btn-primary text-white btn-outline w-full">
                        Sign in
                    </button>
                </Link>
            </div>
        </div>
    </div>
);
Enter fullscreen mode Exit fullscreen mode

};
export default RegisterPage;
`

Collapse
 
loopmode profile image
Jovica Aleksic • Edited

Please note that you can NOT use a hook in class-based components, as is stated here. Functional components only.

Collapse
 
salehmubashar profile image
Saleh Mubashar • Edited

Yes you are right, i forgot to mention that

Collapse
 
cgitosh profile image
Clement Gitonga

What if you want to pass data to the next page? for example select a record from a grid then open edit page passing the selected data

Collapse
 
omoluabii profile image
Hammed A • Edited

Yes, you can pass data
navigate("/todos", { state: { newId: id } })

Collapse
 
abssaxon profile image
Abhinav Saxena

How do we get this state on the receiving end?

Collapse
 
darneltaphil profile image
darneltaphil

Can I use useNavigate to send props to the page I am redirecting to?

Collapse
 
omoluabii profile image
Hammed A

Yes, you can pass props

Collapse
 
abssaxon profile image
Abhinav Saxena

How do we pass state with useNavigation and receive it on the other end?