1

I create a basic log page in react where on login it will redirect me to the next component I use react-router v5.3 it is showing an error cannot read properties of undefined (reading 'push') how can I resolve this error

import React, {useState} from 'react'
import {useHistory,} from 'react-router-dom';


    export default function Loginpage() {
    const history = useHistory();

    //set the initial sate for the inputs
    const [username, setusername] = useState('');
    const [password, setpassword] = useState('');

    //function to handle form submission
    const handleFormSubmit = (event) => {

        event.preventDefault();// prevent from refreshing the page

        //checck the user name and password 
        if (username === 'employee' && password === 'emp123'){
            history.push('./components/JobFindPage');
            alert('hii');
        }
        else  if (username === 'employer' && password === 'emr123'){
            history.push('/CreateJobPage');
            alert('hii');
        }
        else{
            alert ('wrong username or password')
        }
    }


    return (
        <>
            <form onSubmit = {handleFormSubmit}>
                <label>
                    Username :
                    <input type="text" value={username} onChange={(e) => setusername(e.target.value)} /> <br />
                </label>
                <label>
                    Password :
                    <input type="text" value={password} onChange={(e) => setpassword(e.target.value)} /> <br />
                </label>
                <button type="submit">Log IN</button>
            </form>
        </>
    );
}

I expected that using history push(/component) will redirect me to that component

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Law Lite
  • 19
  • 1
  • I don't see any overt issue with the `useHistory` hook and usage. Think you could create a ***running*** [codesandbox](https://codesandbox.io/) demo that reproduces this issue that we could inspect live? – Drew Reese Apr 05 '23 at 05:47
  • can you tell me how can i do it – Law Lite Apr 05 '23 at 06:00
  • 1
    How to create a codesandbox? Click that link, create a new workspace using the React template, and start copy/pasting your code. It's an online IDE that is effectively a VsCode clone. Once your code is in place, please double-check the package dependencies to ensure they match what you are using locally. – Drew Reese Apr 05 '23 at 06:03
  • here is every thing that I did https://codesandbox.io/embed/charming-leaf-3tnumh?fontsize=14&hidenavigation=1&theme=dark – Law Lite Apr 05 '23 at 06:57

1 Answers1

0

The app is missing rendering a router to provide a routing context and history object.

Import a router and wrap the App component.

Example:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>
);

Since you are using react@18 and rendering the app into a React.StrictMode component you'll also want to bump to at least react-router-dom@5.3.3 to resolve a compatibility issue between React 18 and RRDv5.

The Login component also should navigate to paths the app is rendering routes for. history.push("./components/JobFindPage"); will incorrectly append "/components/JobFindPage" to the end of the current URL path.

import React, { useState } from "react";
import { useHistory } from "react-router-dom";

export default function LoginPage() {
  const history = useHistory();

  //set the initial sate for the inputs
  const [username, setusername] = useState("");
  const [password, setpassword] = useState("");

  //function to handle form submission
  const handleFormSubmit = (event) => {
    event.preventDefault(); // prevent from refreshing the page

    //checck the user name and password
    if (username === "employee" && password === "emp123") {
      history.push("/JobFindPage"); // <-- fix this path
      alert("hii");
    } else if (username === "employer" && password === "emr123") {
      history.push("/CreateJobPage");
      alert("hii");
    } else {
      alert("wrong username or password");
    }
  };

  return (
    <>
      <form onSubmit={handleFormSubmit}>
        <label>
          Username :
          <input
            type="text"
            value={username}
            onChange={(e) => setusername(e.target.value)}
          />{" "}
          <br />
        </label>
        <label>
          Password :
          <input
            type="text"
            value={password}
            onChange={(e) => setpassword(e.target.value)}
          />{" "}
          <br />
        </label>
        <button type="submit">Log IN</button>
      </form>
    </>
  );
}

Edit ecstatic-khayyam-zj0t3l

Drew Reese
  • 165,259
  • 14
  • 153
  • 181