Next.js Discord

Discord Forum

Router don't want to route !

Answered
Ninhache posted this in #help-forum
Open in Discord
In a client component..
I'm on the path /?login=true
How can i navigate to /?login=false ?
router.push('/?login=false') not working.. may it's because searchParams are changing.. but the path isnt..

25 Replies

@Ninhache In a client component.. I'm on the path `/?login=true` How can i navigate to `/?login=false` ? `router.push('/?login=false')` not working.. may it's because searchParams are changing.. but the path isnt..
there's an example in the docs which i slightly modified

here's what you need to do

"use client";

import { useCallback } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";

export default function Example() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams()!;

  // Get a new searchParams string by merging the current
  // searchParams with a provided key/value pair
  const createQueryString = useCallback(
    (name: string, value: string) => {
      const params = new URLSearchParams(searchParams);
      params.set(name, value);

      return params.toString();
    },
    [searchParams]
  );

  return (
    <>
      <p>Sort By</p>

      {/* using useRouter */}
      <button
        onClick={() => {
          // <pathname>?sort=asc
          router.push(pathname + "?" + createQueryString("login", "true"));
        }}
      >
        Login true
      </button>

      {/* using <Link> */}
      <Link
        href={
          // <pathname>?sort=desc
          pathname + "?" + createQueryString("login", "false")
        }
      >
        Login false
      </Link>
    </>
  );
}
still the same ? you're sure it's shoulds work :/?
not-working example 😬
@Dayo where are you changing to ?login=false?
in the header component
but it's a simple router.push("/number");
look the file ./components/Header.jsx
@Ninhache but it's a simple `router.push("/number");`
i can see it on the onclose. but how do you close?
by clicking outside of the modal sry
nothing happens when i click outside
lol no way that's the pb
u get console log
the router.push isnt working
Answer
wtf
wtf did u change
literally used the code i sent above
then i removed the Modal from inside the Link.
you should render the Modal apart else the onClose won't work
i mean the router.push
Ahhh..
Explanation :
Don't put anything in links.. apparently they're catching routers actions and that's why i've got blocked