You are an expert software engineer specialised in Next.js 14 with TypeScript and…
- User
You are an expert software engineer specialised in Next.js 14 with TypeScript and TailwindCSS. I need you to add an animation when my Feedback component mounts and unmounts.
app/submissions/[submissionUrl]/mark/[assessmentId]/feedbacks.tsx
"use client"; import { IQuestionBranch } from "@/app/actions/server/default.action"; import useVisibleElements from "@/hooks/visible-elements.hook"; import React, { useMemo, useState } from "react"; import Feedback from "./feedback"; import { IContent } from "@/database/schemas/content.schema"; import { createHierarchicalLabel } from "@/lib/utils"; interface IProps { question: IQuestionBranch; dependency: { [key: string]: string }; } const Feedbacks = ({ question, dependency }: IProps) => { const visibleElementIds = useVisibleElements(); const [feedbacks, setFeedbacks] = useState(initFeedbacks(question)); const [activeFeedback, setActiveFeedback] = useState<string | null>(null); // eslint-disable-next-line const visibleQuestionIds = useMemo(() => getVisibleQuestionIds(dependency, visibleElementIds), [visibleElementIds]); const visibleFeedbacks = feedbacks.filter((el) => visibleQuestionIds.indexOf(el.questionId) !== -1); return ( <> {visibleFeedbacks.map((el) => ( <Feedback key={`question-${el.questionId}-feedback`} isActive={activeFeedback === el.questionId} onClick={setActiveFeedback.bind(this, el.questionId)} {...el} /> ))} </> ); }; export default Feedbacks; export interface IFeedback { questionId: string; label: string; grade: string; feedback: IContent[]; } const initFeedbacks = (question: IQuestionBranch): IFeedback[] => { const newFeedbacks: IFeedback[] = []; const addFeedback = (feedbacks: IFeedback[], questionBranch: IQuestionBranch, trail: number[] = []): void => { if (questionBranch.grade === undefined || !questionBranch.feedback) throw new Error(""); feedbacks.push({ questionId: questionBranch.id, label: trail.length > 0 ? `Question ${createHierarchicalLabel(trail)}` : "Assessment", grade: questionBranch.grade, feedback: questionBranch.feedback, }); for (let i = 0; i < questionBranch.questions.length; i++) { addFeedback(feedbacks, questionBranch.questions[i], [...trail, i]); } }; addFeedback(newFeedbacks, question); return newFeedbacks; }; const getVisibleQuestionIds = (dependency: { [key: string]: string }, visibleElementIds: string[]): string[] => { // Convert the visibleElementIds array to a Set for efficient lookups const visibleSet = new Set(visibleElementIds); // Iterate over the keys of the dependency object // and filter keys whose corresponding value is in the visibleSet return Object.keys(dependency).filter((key) => visibleSet.has(dependency[key])); };app/submissions/[submissionUrl]/mark/[assessmentId]/feedback.tsx
import ContentsView from "@/components/c-ui/contents/view"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import React from "react"; import { IFeedback } from "./feedbacks"; import { IContent } from "@/database/schemas/content.schema"; interface IProps extends IFeedback { isActive: boolean; onClick: () => void; } const Feedback = ({ questionId, label, grade, feedback, isActive, onClick }: IProps) => { const state: "empty" | "preview" | "active" = isActive ? "active" : !grade && !feedback.length ? "empty" : "preview"; let description: string; switch (state) { case "empty": description = "Add feedback"; break; case "preview": description = "Edit feedback"; break; case "active": description = "Editing in progress"; break; default: throw new Error(""); } return ( <Card className="opacity-60 hover:opacity-100" onClick={onClick}> <CardHeader> <CardTitle>{label}</CardTitle> <CardDescription>{description}</CardDescription> </CardHeader> {state === "preview" && <Preview questionId={questionId} grade={grade} feedback={feedback} />} </Card> ); }; export default Feedback; interface IPreviewProps { questionId: string; grade: string; feedback: IContent[]; } const Preview = ({ questionId, grade, feedback }: IPreviewProps) => { return ( <CardContent className="h-fit w-full flex flex-col"> <p> Grade: <span>{grade}</span> </p> <p>Feedback:</p> <ContentsView keyPrefix={`question-${questionId}-feedback`} contents={feedback} /> </CardContent> ); }; - Assistant
To add smooth mount and unmount animations to your
Feedbackcomponents in a Next.js 14 application using TypeScript and TailwindCSS, the Framer Motion library is an excellent choice. It integrates seamlessly with React, providing powerful and declarative animations.Here's a step-by-step guide to implementing these animations:
-
Install Framer Motion
First, you'll need to add
framer-motionto your project. You can do this using npm or yarn:npm install framer-motion # or yarn add framer-motion -
Update
FeedbacksComponent to UseAnimatePresenceThe
AnimatePresencecomponent from Framer Motion enables animations for components that are conditionally rendered (i.e., mounted and unmounted). Wrap your mappedFeedbackcomponents withAnimatePresenceand convert eachFeedbackto amotion.divto apply animations.Updated
feedbacks.tsx:"use client"; import { IQuestionBranch } from "@/app/actions/server/default.action"; import useVisibleElements from "@/hooks/visible-elements.hook"; import React, { useMemo, useState } from "react"; import Feedback from "./feedback"; import { IContent } from "@/database/schemas/content.schema"; import { createHierarchicalLabel } from "@/lib/utils"; import { AnimatePresence } from "framer-motion"; interface IProps { question: IQuestionBranch; dependency: { [key: string]: string }; } const Feedbacks = ({ question, dependency }: IProps) => { const visibleElementIds = useVisibleElements(); const [feedbacks, setFeedbacks] = useState(initFeedbacks(question)); const [activeFeedback, setActiveFeedback] = useState<string | null>(null); // eslint-disable-next-line const visibleQuestionIds = useMemo(() => getVisibleQuestionIds(dependency, visibleElementIds), [visibleElementIds]); const visibleFeedbacks = feedbacks.filter((el) => visibleQuestionIds.indexOf(el.questionId) !== -1); return ( <AnimatePresence> {visibleFeedbacks.map((el) => ( <Feedback key={`question-${el.questionId}-feedback`} isActive={activeFeedback === el.questionId} onClick={() => setActiveFeedback(el.questionId)} {...el} /> ))} </AnimatePresence> ); }; export default Feedbacks; export interface IFeedback { questionId: string; label: string; grade: string; feedback: IContent[]; } const initFeedbacks = (question: IQuestionBranch): IFeedback[] => { const newFeedbacks: IFeedback[] = []; const addFeedback = (feedbacks: IFeedback[], questionBranch: IQuestionBranch, trail: number[] = []): void => { if (questionBranch.grade === undefined || !questionBranch.feedback) throw new Error(""); feedbacks.push({ questionId: questionBranch.id, label: trail.length > 0 ? `Question ${createHierarchicalLabel(trail)}` : "Assessment", grade: questionBranch.grade, feedback: questionBranch.feedback, }); for (let i = 0; i < questionBranch.questions.length; i++) { addFeedback(feedbacks, questionBranch.questions[i], [...trail, i]); } }; addFeedback(newFeedbacks, question); return newFeedbacks; }; const getVisibleQuestionIds = (dependency: { [key: string]: string }, visibleElementIds: string[]): string[] => { // Convert the visibleElementIds array to a Set for efficient lookups const visibleSet = new Set(visibleElementIds); // Iterate over the keys of the dependency object // and filter keys whose corresponding value is in the visibleSet return Object.keys(dependency).filter((key) => visibleSet.has(dependency[key])); };Key Changes:
- Import
AnimatePresence: This component enables the animation of components as they enter and leave the DOM. - Wrap
visibleFeedbacks.mapwith<AnimatePresence>: This ensures that the animations are applied when feedbacks are added or removed. - Update
onClickHandler: Changed to an arrow function for better practice and to ensure proper binding.
- Import
-
Update the
FeedbackComponent to Usemotion.divAnimate each
Feedbackcomponent by converting it to amotion.divand defining the desired animation properties using Framer Motion's props such asinitial,animate, andexit.Updated
feedback.tsx:import ContentsView from "@/components/c-ui/contents/view"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import React from "react"; import { IFeedback } from "./feedbacks"; import { IContent } from "@/database/schemas/content.schema"; import { motion } from "framer-motion"; interface IProps extends IFeedback { isActive: boolean; onClick: () => void; } const Feedback = ({ questionId, label, grade, feedback, isActive, onClick }: IProps) => { const state: "empty" | "preview" | "active" = isActive ? "active" : !grade && !feedback.length ? "empty" : "preview"; let description: string; switch (state) { case "empty": description = "Add feedback"; break; case "preview": description = "Edit feedback"; break; case "active": description = "Editing in progress"; break; default: throw new Error(""); } return ( <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }} transition={{ duration: 0.3 }} > <Card className={`opacity-60 hover:opacity-100 ${isActive ? "shadow-lg" : ""}`} onClick={onClick}> <CardHeader> <CardTitle>{label}</CardTitle> <CardDescription>{description}</CardDescription> </CardHeader> {state === "preview" && <Preview questionId={questionId} grade={grade} feedback={feedback} />} </Card> </motion.div> ); }; export default Feedback; interface IPreviewProps { questionId: string; grade: string; feedback: IContent[]; } const Preview = ({ questionId, grade, feedback }: IPreviewProps) => { return ( <CardContent className="h-fit w-full flex flex-col"> <p> Grade: <span>{grade}</span> </p> <p>Feedback:</p> <ContentsView keyPrefix={`question-${questionId}-feedback`} contents={feedback} /> </CardContent> ); };Key Changes:
-
Import
motion: This allows us to use animated elements. -
Wrap the
Cardwithmotion.div: Defines the animation properties for mounting and unmounting. -
Define Animation Props:
initial: The starting state of the component before the animation begins (opacity: 0, slightly translated down withy: 10).animate: The state to animate to when the component mounts (opacity: 1,y: 0).exit: The state to animate to when the component unmounts (opacity: 0, slightly translated up withy: -10).transition: Defines the duration and easing of the animation.
-
Optional Styling Enhancements:
- Added a conditional
shadow-lgclass when theFeedbackis active to give a subtle emphasis effect.
- Added a conditional
-
-
Optional: TailwindCSS for Additional Styling
If you wish to customize the animation further or add TailwindCSS utilities for smoother transitions, you can adjust the
classNameprops accordingly. However, Framer Motion handles most of the animation logic, and TailwindCSS is primarily used here for static styling (like hover effects). -
Final
feedbacks.tsxandfeedback.tsxwith AnimationsHere's the complete updated code for both components incorporating the animations:
app/submissions/[submissionUrl]/mark/[assessmentId]/feedbacks.tsx"use client"; import { IQuestionBranch } from "@/app/actions/server/default.action"; import useVisibleElements from "@/hooks/visible-elements.hook"; import React, { useMemo, useState } from "react"; import Feedback from "./feedback"; import { IContent } from "@/database/schemas/content.schema"; import { createHierarchicalLabel } from "@/lib/utils"; import { AnimatePresence } from "framer-motion"; interface IProps { question: IQuestionBranch; dependency: { [key: string]: string }; } const Feedbacks = ({ question, dependency }: IProps) => { const visibleElementIds = useVisibleElements(); const [feedbacks, setFeedbacks] = useState(initFeedbacks(question)); const [activeFeedback, setActiveFeedback] = useState<string | null>(null); // eslint-disable-next-line const visibleQuestionIds = useMemo(() => getVisibleQuestionIds(dependency, visibleElementIds), [visibleElementIds]); const visibleFeedbacks = feedbacks.filter((el) => visibleQuestionIds.indexOf(el.questionId) !== -1); return ( <AnimatePresence> {visibleFeedbacks.map((el) => ( <Feedback key={`question-${el.questionId}-feedback`} isActive={activeFeedback === el.questionId} onClick={() => setActiveFeedback(el.questionId)} {...el} /> ))} </AnimatePresence> ); }; export default Feedbacks; export interface IFeedback { questionId: string; label: string; grade: string; feedback: IContent[]; } const initFeedbacks = (question: IQuestionBranch): IFeedback[] => { const newFeedbacks: IFeedback[] = []; const addFeedback = (feedbacks: IFeedback[], questionBranch: IQuestionBranch, trail: number[] = []): void => { if (questionBranch.grade === undefined || !questionBranch.feedback) throw new Error(""); feedbacks.push({ questionId: questionBranch.id, label: trail.length > 0 ? `Question ${createHierarchicalLabel(trail)}` : "Assessment", grade: questionBranch.grade, feedback: questionBranch.feedback, }); for (let i = 0; i < questionBranch.questions.length; i++) { addFeedback(feedbacks, questionBranch.questions[i], [...trail, i]); } }; addFeedback(newFeedbacks, question); return newFeedbacks; }; const getVisibleQuestionIds = (dependency: { [key: string]: string }, visibleElementIds: string[]): string[] => { // Convert the visibleElementIds array to a Set for efficient lookups const visibleSet = new Set(visibleElementIds); // Iterate over the keys of the dependency object // and filter keys whose corresponding value is in the visibleSet return Object.keys(dependency).filter((key) => visibleSet.has(dependency[key])); };app/submissions/[submissionUrl]/mark/[assessmentId]/feedback.tsximport ContentsView from "@/components/c-ui/contents/view"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import React from "react"; import { IFeedback } from "./feedbacks"; import { IContent } from "@/database/schemas/content.schema"; import { motion } from "framer-motion"; interface IProps extends IFeedback { isActive: boolean; onClick: () => void; } const Feedback = ({ questionId, label, grade, feedback, isActive, onClick }: IProps) => { const state: "empty" | "preview" | "active" = isActive ? "active" : !grade && !feedback.length ? "empty" : "preview"; let description: string; switch (state) { case "empty": description = "Add feedback"; break; case "preview": description = "Edit feedback"; break; case "active": description = "Editing in progress"; break; default: throw new Error(""); } return ( <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }} transition={{ duration: 0.3 }} > <Card className={`opacity-60 hover:opacity-100 ${isActive ? "shadow-lg" : ""}`} onClick={onClick}> <CardHeader> <CardTitle>{label}</CardTitle> <CardDescription>{description}</CardDescription> </CardHeader> {state === "preview" && <Preview questionId={questionId} grade={grade} feedback={feedback} />} </Card> </motion.div> ); }; export default Feedback; interface IPreviewProps { questionId: string; grade: string; feedback: IContent[]; } const Preview = ({ questionId, grade, feedback }: IPreviewProps) => { return ( <CardContent className="h-fit w-full flex flex-col"> <p> Grade: <span>{grade}</span> </p> <p>Feedback:</p> <ContentsView keyPrefix={`question-${questionId}-feedback`} contents={feedback} /> </CardContent> ); }; -
Testing the Animations
After implementing the above changes, test your application to ensure that:
- Mount Animation: When a
Feedbackcomponent becomes visible (e.g., whenvisibleFeedbackschanges), it should smoothly fade in and slide up from the bottom. - Unmount Animation: When a
Feedbackcomponent is removed fromvisibleFeedbacks, it should smoothly fade out and slide up slightly.
Sample Visual Flow:
- Mounting: The
Feedbackcard transitions from{ opacity: 0, y: 10 }to{ opacity: 1, y: 0 }, creating a fade-in and upward motion. - Unmounting: The
Feedbackcard transitions from{ opacity: 1, y: 0 }to{ opacity: 0, y: -10 }, creating a fade-out and slight upward motion.
- Mount Animation: When a
-
Customizing Animations
Framer Motion offers a vast range of customization options. You can adjust the
transitionproperty to modify the duration, easing, or add delays. Additionally, you can experiment with different animation properties like scaling, rotating, or adding stagger effects for multiple components.Example: Adding a Scale Effect
<motion.div initial={{ opacity: 0, y: 10, scale: 0.95 }} animate={{ opacity: 1, y: 0, scale: 1 }} exit={{ opacity: 0, y: -10, scale: 0.95 }} transition={{ duration: 0.3, ease: "easeInOut" }} > {/* ... */} </motion.div>This adds a subtle scaling effect, making the
Feedbackcard appear slightly larger as it mounts and smaller as it unmounts. -
Handling Conditional Rendering inside
Feedback(Optional)If you have elements within the
Feedbackcomponent that also conditionally render (like thePreviewcomponent), you can similarly wrap them withAnimatePresenceand use Framer Motion animations to handle their mount and unmount transitions.Example: Animating the
PreviewComponentimport { motion, AnimatePresence } from "framer-motion"; // Inside the Feedback component's return statement <AnimatePresence> {state === "preview" && ( <motion.div key="preview" initial={{ height: 0, opacity: 0 }} animate={{ height: "auto", opacity: 1 }} exit={{ height: 0, opacity: 0 }} transition={{ duration: 0.3 }} > <Preview questionId={questionId} grade={grade} feedback={feedback} /> </motion.div> )} </AnimatePresence>This ensures that the
Previewsection also animates in and out smoothly.
By following these steps, your
Feedbackcomponents will have smooth and visually appealing mount and unmount animations, enhancing the overall user experience of your application. -