I am trying to make a login modal popup which will show on click of a button inside of a navbar. However, I am getting below error:
TypeError: setOpenModal is not a function
Even after looking at many threads here, I am unable to understand what is causing the error in my case. Below is my code:
Navbar.js:
import React, { useState } from "react";
import { Link } from "react-router-dom";
import "./Navbar.css";
import Login from "./Login";
function Navbar() {
const [openModal, setOpenModal] = useState(false);
const showModal = () => {
setOpenModal(true);
};
return (
<nav className="navbar">
<div className="nav-div">
<Link to="/" className="nav-logo">
<i class="fas fa-hamburger"></i>Hungermania
</Link>
<div className="nav-form">
<form>
<input
className="nav-search"
type="search"
placeholder="Search for your favorite restaurant, cuisine or a dish"
></input>
<button className="btn-search">Search</button>
</form>
</div>
<ul>
<li className="nav-item">
<button className="login-btn nav-link" onClick={showModal}>
Login
</button>
{openModal && <Login setOpenModal={setOpenModal} />}
</li>
<li className="nav-item">
<button className="signup-btn nav-link">Sign Up</button>
</li>
</ul>
</div>
</nav>
);
}
export default Navbar;
Login.js:
import React from "react";
import "./Login.css";
function Login({ setOpenModal }) {
const hideModal = () => {
setOpenModal(false);
};
return (
<div className="modalBackground">
<div className="modalContainer">
<div className="titleclosebtn">
<button onClick={hideModal}>×</button>
</div>
<div className="title">
<h1>Login</h1>
</div>
<div className="body">
<form>
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" required />
<br />
<br />
<label for="phone">Phone No:</label>
<input type="number" placeholder="Phone No." required />
<br />
<br />
<label for="email">Email Id:</label>
<input type="email" placeholder="[email protected]" required />
<br />
<br />
<div className="footer">
<button type="submit" class="btn-signup">
SIGN UP
</button>
</div>
</form>
</div>
</div>
</div>
);
}
export default Login;
CodePudding user response:
There's nothing wrong with ur code, so it was prob cash or something.
restarting server should stop accusing that error.
Normally when stupid errors like this happens, i just comment that part that is accusing error, wait refresh and uncomment, that works too instead of always restarting server.
CodePudding user response:
{openModal && <Login setOpenModal={setOpenModal} />}
this part of the code. You are passing down a prop named setOpenModal
and you are passing down setOpenModal
. You cannot pass down the setter of your state. You can either pass down variables or functions with props. So create a function, in that function you can use setOpenModal
and then pass that function down like this:
const someFunction=(value)=>{
setOpenModal(value);
}
{openModal && <Login whatEverName={someFunction} />}