Next.js Discord

Discord Forum

How do I redirect to a functionally different page (without reloading the page) in Nextjs?

Unanswered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
Hello, I am trying to functionally redirect to different page in nextjs. The redirection is successful but the page is reloaded. I tried react-router-dom, but this doesn't work. I searched on the github but couldn't find any result. Is there any way to do this?

import { useRouter } from "next/navigation";


const router = useRouter();


loginSchema.validate(formData, { abortEarly: false })
                .then(() => {
                  setIsLoading(true);
                  Login(formData)
                    .then((res) => {
                      console.log(res);
                      router.push("/");
                    })
                    .catch((err) => {})
                    .finally(() => {
                      setIsLoading(false);
                    });
                })

4 Replies

Mud-daubers
use preventDefault();
@Mud-daubers use preventDefault();
Masai LionOP
How do I apply this to the router? Does this trigger a submit event?
@Mud-daubers use preventDefault();
Masai LionOP
onSubmit={(e) => {
          e.preventDefault();
          loginSchema
            .validate(formData, { abortEarly: false })
            .then((e) => {
              setIsLoading(true);
              Login(formData)
                .then((res) => {
                  setTimeout(() => {
                    router.push("/land/add");
                  }, 3000);
                })
                .catch((err) => {})
                .finally(() => {
                  setIsLoading(false);
                });
            })
            .catch((errors) => {
              const schemaErrors = errors.inner.map((err) => {
                return { name: err.path, message: err.message };
              });
              if (schemaErrors.length > 0) {
                const element = document.getElementsByName(
                  schemaErrors[0].name
                );
                if (element.length > 0)
                  element[0].scrollIntoView({
                    behavior: "smooth",
                    block: "center",
                  });
              }
              setErrors(schemaErrors);
            });
        }}


i tried like this. but after 3 secons its still refreshing page
Masai LionOP
I realised that the problem was that switching between different layouts caused the page to fully load.