Search code examples
javascriptreactjsreact-hooksreact-router-dom

Why <Navigate to="" /> is not working but console.log("Authentication successful!"); is working


import Typewriter from "typewriter-effect";
import { Navigate } from "react-router-dom";
import { useState } from "react";

const Login = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const handleUsernameChange = (event) => {
    setUsername(event.target.value);
  };

  const handlePasswordChange = (event) => {
    setPassword(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    if (username === "name" && password === "123") {
      // Authentication successful - redirect to home page
      console.log("Authentication successful!");
      return <Navigate to="/home" />;
    } else {
      // Authentication failed - display an error message
      console.log("Authentication failed!");
    }
  };

  return (
    <div className="flex justify-center items-center w-full h-screenw-full h-screen bg-gradient-to-r from-lime-700 via-orange-900 to-red-800">
      <div className=" w-[500px] h-[490px] text-white bg-black/20 rounded-2xl">
        <div className="w-[400px] py-10 mx-auto">
          <form onSubmit={handleSubmit} className="text-black">
            <label>
              Username:
              <input
                type="text"
                value={username}
                onChange={handleUsernameChange}
              />
            </label>
            <br />
            <label>
              Password:
              <input
                type="password"
                value={password}
                onChange={handlePasswordChange}
              />
            </label>
            <br />
            <button
            >
              Submit
            </button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Login;

The console.log is working for both if condition but <Navigate to="/home" \> is not working is there any way to resolve this error, tried return <Navigate to="/home" \> without using if statement and it works, its not working in if statement, why this happens? ‎ ‎


Solution

  • You can't return JSX from a callback like this and expect it to be rendered and do anything. The Navigate component issues a declarative navigation action and must be rendered with the component render, e.g. part of the returned JSX from the function component.

    If you want to invoke a navigation action from a callback then use the useNavigate hook and issue an imperative navigation action.

    Example:

    import { useNavigate } from "react-router-dom"; // <-- import hook
    
    const Login = () => {
      const navigate = useNavigate(); // <-- call hook
    
      ...
    
      const handleSubmit = (event) => {
        event.preventDefault();
        if (username === "name" && password === "123") {
          // Authentication successful - redirect to home page
          console.log("Authentication successful!");
          navigate("/home"); // <-- issue navigation action
        } else {
          // Authentication failed - display an error message
          console.log("Authentication failed!");
        }
      };
    
      ...