I'm trying to make a login page that navigates to another page when the Submit button is clicked using ReactJS. but I encountered a few problems:
it looks like the event handler function gets called right away when the page loads because the console.log('clicked') appears in the developer tools before I do anything
when I actually clicked the Submit button, the page doesn't change.
when the page changes (or loads), there's a warning in the developer tools saying
No routes matched location "/"
in Routes (created by App)
in App
although there are already paths for / and /dashboard in the <Routes> in App.js
here's my code (and here's the CodeSandbox):
// ./App.js
import { HashRouter as Router, Route, Routes } from "react-router-dom";
import Login from "./components/Login";
import Dashboard from "./components/Dashboard";
export default function App() {
return (
<Router>
<div className="App">
<h1>Hello CodeSandbox</h1>
<Routes>
<Route path="/" element={<Login />} />
</Routes>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</div>
</Router>
);
}
// ./components/Login.js
import { Button } from "react-bootstrap";
import { useNavigate } from "react-router-dom";
const Login = () => {
const navigate = useNavigate();
const handleClick = (e) => {
console.log("clicked");
navigate("/dashboard");
};
return (
<div>
<form>
<h2>The Login page</h2>
<Button variant="primary" onClick={handleClick()}>
Submit
</Button>
</form>
</div>
);
};
export default Login;
// ./components/Dashboard.js
import React from "react";
const Dashboard = () => {
return (
<div>
<h2>This is the Dashboard page</h2>
</div>
);
};
export default Dashboard;
It’s because you are directly calling function
onClick = {()=> handleClick(“send anything here”)}