You are an expert software engineer specialised in Next.js 14 with TypeScript. I will share you my code implementations. I'll need you to resolve an error that I am encountering.
"use client";
import React, { useMemo } from "react";
import useScreenWidth from "../../hooks/screen-width.hook";
/**
* Defines the possible TailwindCSS breakpoints.
*/
type Breakpoint = "base" | "sm" | "md" | "lg" | "xl" | "2xl";
/**
* Props interface for the Container component.
*
* @template P - The type of the props expected by the child component.
*/
interface ContainerProps<P> {
/**
* The child component to be rendered within the container.
*/
childComponent: React.ComponentType<P>;
/**
* An array of props that will be passed to each child component.
*/
propsArray: P[];
/**
* A prefix string to ensure unique keys for each child component.
*/
keyPrefix: string;
/**
* The invisible component to fill empty spots in a row.
* This ensures consistent spacing by occupying space similar to child components.
*/
widthInvisible: string;
/**
* An object specifying the number of children per row for each TailwindCSS breakpoint.
* Example:
* {
* base: 1,
* md: 2,
* xl: 3
* }
*/
childrenPerRow?: Partial<Record<Breakpoint, number>>;
}
/**
* Container component to display child components in a responsive, wrapping layout.
* Ensures space-between behavior for each row with customizable gaps and fills empty spaces with an invisible component.
*
* @template P - The type of the props expected by the child component.
*
* @param {ContainerProps<P>} props - The props for the Container component.
*
* @returns {JSX.Element} The rendered Container component.
*/
const Container = <P,>({
childComponent: ChildComponent,
propsArray,
keyPrefix,
widthInvisible,
childrenPerRow,
}: ContainerProps<P>): JSX.Element => {
// Determine screen size using the useScreenWidth hook for each breakpoint
const is2xl = useScreenWidth("2xl");
const isXl = useScreenWidth("xl");
const isLg = useScreenWidth("lg");
const isMd = useScreenWidth("md");
const isSm = useScreenWidth("sm");
/**
* Determines the current number of children per row based on the active breakpoint.
* It checks from the largest breakpoint to the smallest to find the highest matching breakpoint.
*/
const numberOfChildrenPerRow = useMemo(() => {
if (is2xl && childrenPerRow?.["2xl"]) {
return childrenPerRow["2xl"]!;
} else if (isXl && childrenPerRow?.["xl"]) {
return childrenPerRow["xl"]!;
} else if (isLg && childrenPerRow?.["lg"]) {
return childrenPerRow["lg"]!;
} else if (isMd && childrenPerRow?.["md"]) {
return childrenPerRow["md"]!;
} else if (isSm && childrenPerRow?.["sm"]) {
return childrenPerRow["sm"]!;
} else {
return childrenPerRow?.["base"] ?? 1; // Default to 1 if 'base' is not specified
}
}, [is2xl, isXl, isLg, isMd, isSm, childrenPerRow]);
/**
* Groups the propsArray into chunks based on the numberOfChildrenPerRow.
* Each chunk represents a row of child components.
*/
const rows: P[][] = useMemo(() => {
const tempRows: P[][] = [];
for (let i = 0; i < propsArray.length; i += numberOfChildrenPerRow) {
tempRows.push(propsArray.slice(i, i + numberOfChildrenPerRow));
}
return tempRows;
}, [propsArray, numberOfChildrenPerRow]);
/**
* Generates required number of invisible components to fill the empty spots in a row.
*
* @param {number} missingCount - The number of invisible components needed.
* @param {number} rowIndex - The index of the current row.
*
* @returns {JSX.Element[]} An array of invisible components.
*/
const renderInvisibleComponents = (missingCount: number, rowIndex: number): JSX.Element[] => {
return Array.from({ length: missingCount }, (_, idx) => (
<div key={`${keyPrefix}-invisible-${rowIndex}-${idx}`} className={`invisible ${widthInvisible}`} />
));
};
return (
<div className="h-fit w-full flex flex-col gap-8">
{rows.map((row, rowIndex) => {
const missingCount = numberOfChildrenPerRow - row.length;
return (
<div key={`${keyPrefix}-row-${rowIndex}`} className="h-fit w-full flex justify-between gap-8 lg:gap-10 xl:gap-12">
{row.map((childProps, childIndex) => (
<ChildComponent key={`${keyPrefix}-${rowIndex}-${childIndex}`} {...childProps} />
))}
{missingCount > 0 && renderInvisibleComponents(missingCount, rowIndex)}
</div>
);
})}
</div>
);
};
export default Container;
⨯ Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.
<... childComponent={function Submission} propsArray=... keyPrefix=... widthInvisible=... childrenPerRow=...>
^^^^^^^^^^^^^^^^^^^^^
at stringify (<anonymous>)
digest: "860459365"
The error you're encountering stems from the interaction between Server Components and Client Components in Next.js 14. Specifically, you're attempting to pass a Server Component (Submission) as a prop to a Client Component (Container), which Next.js disallows for security and performance reasons.
Let's break down the issue and provide a step-by-step solution to resolve it.
Understanding the Error
Error Message:
code
⨯ Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.
<... childComponent={function Submission} propsArray=... keyPrefix=... widthInvisible=... childrenPerRow=...>
^^^^^^^^^^^^^^^^^^^^^
at stringify (<anonymous>)
digest: "860459365"
Root Cause:
page.tsx is a Server Component by default (since it doesn't have the "use client" directive).
Container is a Client Component (it includes "use client" at the top).
You're passing the Submission component (a Server Component) as a prop (childComponent) to the Client Component (Container).
Next.js restricts passing functions or Server Components directly to Client Components to prevent potential security risks and ensure optimal performance.
Step-by-Step Solution
To resolve this, we'll separate the concerns between Server and Client Components by:
Keeping Data Fetching in the Server Component (page.tsx).
Rendering UI in a Client Component that receives the data as props.
Ensuring all components involved in the UI rendering are Client Components.
1. Convert Submission to a Client Component
Since Submission is being rendered within a Client Component (Container), it needs to be a Client Component itself.
Next, create a Client Component that handles rendering the Container with the Submission components. This separation ensures that only Client Components receive and handle other Client Components.
3. Update page.tsx to Use the New Client Component
Now, modify your Server Component (page.tsx) to pass the data to the newly created Client Component (SubmissionsList) instead of directly passing the Submission component to Container.
Modify app/submissions/page.tsx:
tsx
import Assessment from "@/database/models/assessment.model";
import Attempt from "@/database/models/attempt.model";
import SubmissionModel from "@/database/models/submission.model";
import { getSession } from "@auth0/nextjs-auth0";
import Container from "@/components/c-ui/container"; // This import can be removed if not used elsewhere
import SubmissionsList from "./SubmissionsList"; // Import the new Client Component
import Container from "@/components/c-ui/container"; // Ensure no conflicting imports
import Container from "@/components/c-ui/container";
import connectDb from "@/database/connect";
export default async function Page() {
const session = await getSession();
if (!session) return null;
await connectDb();
const submissions = await SubmissionModel.find(
{ teacherId: session.user.email },
{ _id: 1, title: 1 }
)
.lean()
.exec();
const allAssessments = await Assessment.find(
{ submissionId: { $in: submissions.map((el) => el._id) } },
{ _id: 1, submissionId: 1, questionId: 1 }
)
.lean()
.exec();
const allAttempts = await Attempt.find(
{
assessmentId: { $in: allAssessments.map((el) => el._id) },
questionId: { $in: allAssessments.map((el) => el.questionId) },
},
{ assessmentId: 1, submittedAt: 1, markedAt: 1, verifiedAt: 1 }
)
.lean()
.exec();
const propsArray = submissions.map((el) => {
const assessments = allAssessments
.filter((ele) => ele.submissionId === el._id)
.map((ele) => ele._id);
const attempts = allAttempts.filter((ele) => assessments.includes(ele.assessmentId));
let submittedCount = 0;
let markedCount = 0;
let verifiedCount = 0;
for (let i = 0; i < attempts.length; i++) {
const attempt = attempts[i];
if (attempt.submittedAt) submittedCount++;
if (attempt.markedAt) markedCount++;
if (attempt.verifiedAt) verifiedCount++;
}
return { id: el._id.toString(), title: el.title, submittedCount, markedCount, verifiedCount };
});
return (
<div className="h-full w-full flex shrink-0 overflow-x-hidden overflow-y-auto content-start p-8 lg:p-24 gap-4 lg:gap-8">
<SubmissionsList propsArray={propsArray} />
</div>
);
}
Important Adjustments:
Ensure Data Types are Serializable:
If _id is a ObjectId or another non-serializable type, convert it to a string by using .toString() or similar methods.
Since you're no longer passing childComponent to Container directly from page.tsx, you can remove the import of Container if it's not used elsewhere in page.tsx.
4. Verify the Container Component
Ensure that the Container component is appropriately handling the childComponent prop. Since Container is a Client Component, it should now be receiving a Client Component (Submission) as the childComponent.
Note: If you encounter TypeScript issues after making Submission a Client Component, ensure that all types are correctly defined and that Submission is properly exported as a React component.
Final Structure Overview
Server Component:app/submissions/page.tsx
Responsibilities:
Authenticate user.
Fetch data from the database.
Pass the serialized data (propsArray) to a Client Component.
Define Schemas Properly: Ensure that your Mongoose models (Assessment, Attempt, SubmissionModel) have correctly defined TypeScript interfaces to avoid type mismatches.
Use getServerSession (if applicable): Depending on your Auth setup, consider using getServerSession instead of getSession for better server-side session handling.
3. UI/UX Improvements:
Loading States: Implement loading states in the Client Component (SubmissionsList) to enhance user experience during data fetching.
Error Handling: Incorporate error boundaries or try-catch blocks to gracefully handle any data fetching errors.
By restructuring your components to respect the boundaries between Server and Client Components in Next.js 14, you ensure better performance, security, and maintainability of your application. This approach adheres to Next.js best practices and resolves the error you're encountering.