I am trying to get an authentication in place for a react app that I am building.. Given below is the code I have for my App.js and Auth.js files
When I load my app it says
Too many re-renders. React limits the number of renders to prevent an infinite loop.
Can someone assist on where I could be going wrong here, thanks
Code for App.js
import "./App.css";
import SideBar from "./components/Sidebar/SideBar";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Dashboard from "./pages/Dashboard";
import Report1 from "./pages/Report1";
import Report2 from "./pages/Report2";
import Auth from "./components/Auth";
import { useState, useEffect } from "react";
function App() {
const authToken = false;
return (
<div>
{!authToken && <Auth />}
{authToken && (
<Router>
<SideBar>
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/Report1" element={<Report1 />} />
<Route path="/Report2" element={<Report2 />} />
<Route path="*" element={<> not found</>} />
</Routes>
</SideBar>
</Router>
)}
</div>
);
}
export default App;
Code for Auth.js
import { useState } from "react";
const Auth = () => {
const [isLogin, setIsLogin] = useState(true);
const [error, setError] = useState();
const viewLogin = (status) => {
setError(null);
setIsLogin(status);
};
return (
<div className="auth-container">
<div className="auth-container-box">
<form>
<h2>{isLogin ? "Please log in" : "Please sign up"}</h2>
<input type="email" placeholder="email" />
<input type="password" placeholder="password" />
{!isLogin && <input type="password" placeholder="confirm pass" />}
<input type="submit" className="create" />
{error && <p>{error}</p>}
</form>
<div className="auth-options">
<button
onClick={viewLogin(false)}
>
Sign up
</button>
<button
onClick={viewLogin(true)}
>
Login
</button>
</div>
</div>
</div>
);
};
export default Auth;
3
Answers
These 2 are the culprit:
onClick={viewLogin(false)}
andonClick={viewLogin(true)}
I’m assuming you wrote this thinking how it works in normal HTML. However, this is JSX and writing
onClick={funcName()}
will actually call the function right then when the component renders. What we want to do is give it a function that will be called later when theonClick
event happens.The simple fix:
onClick={()=> viewLogin(false)}
andonClick={()=> viewLogin(true)}
You directly called the functions in your buttons, which will lead to new renders during the rendering phase.
You should switch
with
This way you pass an actual function to the button which will be executed on click and not right away.
The issue causing the "Too many re-renders" error is in the onClick handlers of the buttons in your Auth.js component. When using onClick handlers, you should pass a function reference, but in your code, you are directly invoking the functions, which causes an infinite loop of re-renders.
Corrected code for Auth.js: