I built an app using Next.js v13.4
. Within the app, there is a server component where I fetch all users from the database and display them in individual cards. My goal is to add a delete button to each card, but whenever I try to attach an event listener to the button, I encounter this error:
Unhandled Runtime Error Error: Event handlers cannot be passed to Client Component props.
<button onClick={function} children=...>
^^^^^^^^^^
If you need interactivity, consider converting part of this to a Client Component.
Below is the code snippet for my component:
// import { useRouter } from "next/navigation";
import Link from "next/link";
import dbConnect from "../lib/dbConnect";
import User from "../models/User";
export default async function Home() {
// const router = useRouter();
const data = await getData();
const users = data.props.users;
const handleDelete = async (id: any) => {
try {
await fetch(`/api/users/${id}`, {
method: "Delete",
});
// router.push("/");
} catch (error) {
console.log("error ===> ", error);
}
};
return (
<main className="main">
<h1>Home page</h1>
{users ? (
<div className="users">
{users.map((user) => (
<div key={user._id}>
<div className="card">
<h3 className="user-name">Name: {user.name}</h3>
<p className="email">Email: {user.email}</p>
<p className="email">
Password: {user.password}
</p>
<p className="email">Country: {user.country}</p>
<button onClick={(_id) => handleDelete(_id)}>Delete</button>
</div>
</div>
))}
<Link className="add-btn-link" href="/new">
<div className="add-btn">
<p>+</p>
</div>
</Link>
</div>
) : (
<p>No users</p>
)}
</main>
);
}
async function getData() {
await dbConnect();
/* find all the data in our database */
const result = await User.find({});
const users = result.map((doc) => {
const user = doc.toObject();
user._id = user._id.toString();
return user;
});
return { props: { users: users } };
}
Attached below is a screenshot of the issue:
https://i.sstatic.net/kLLij.png
The error message also mentions that I can't use useRouter(). Here's the specific error:
Error: useRouter only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component
To resolve this, I believe I need to split certain sections into separate components, although the exact approach eludes me.