Search code examples
typescriptnext.jsreact-router-dom

How to change page in next js with react-router-dom


I want to change the page if the login was successful but I get this error message:

enter image description here

with this code:

export default function SignUp() {
  const trigger = async (event: any) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const navigate = useNavigate();
    try {
      const response = await fetchRestEndpoint(`/users`, 'POST', {
        username: data.get("username"),
        email: data.get("email"),
        password: data.get("password"),
        role: "user"
      });
    if (response.ok) {
      const user: any = await response.json();
      console.log(user);
      navigate('/');
    }
  } catch(e) {
    alert(e);
  }
  ......

Solution

  • Next.js provides its own router. You do not need to use react-router-dom. I strongly recommend you take a look at the related documentation.

    When using the pages directory

    import { useCallback } from "react";
    import { useRouter } from "next/router";
    
    const MyComponent = () => {
      const router = useRouter();
    
      const login = useCallback(() => {
        // ...
        router.push("/some-url")
      }, [router]);
    
      return (
        // ...
      );
    }
    

    When using the app directory

    import { useCallback } from "react";
    import { useRouter } from "next/navigation";
    
    const MyComponent = () => {
      const router = useRouter();
    
      const login = useCallback(() => {
        // ...
        router.push("/some-url")
      }, [router]);
    
      return (
        // ...
      );
    }