Is Next.js experiencing issues with animating presence specifically for exit animations?

I'm facing an issue with adding an exit animation to my components in next js. Despite setting an initial animation, the exit animation doesn't seem to work as expected.

Could someone please help me figure out what I'm doing wrong here?

Below is a snippet of my code for reference:

<AnimatePresence >
    <motion.div key="modalBackground" className={styles['auth-modal-layout']} key="modalBackground" initial="hidden" animate="visible" variants={
            {
                hidden:{
                    opacity:0
                },
                visible:{
                    opacity:1,
                    transition:{
                        duration:.4,
                    }
                },
            }
        } >

        <motion.div key="modalForm" className={styles['auth-modal-form']} initial="hidden" exit="pageExit" animate="visible" exit="hidden" variants={{
            hidden:{
                translateY:100,
                opacity:0
            },
            visible:{
                translateY:0,
                opacity:1,
                transition:{
                    duration:.4
                }
            },
            pageExit:{
                opacity:0,
                transition:{
                    when:"afterChildren",
                    duration:.4
                }
            }
        }} >
            {modal()}
        </motion.div>

    </motion.div>
    </AnimatePresence> 

Answer №1

<AnimatePresence> must enclose the component being conditionally rendered, rather than being placed inside it.

To resolve this issue, you can either elevate the <AnimatePresence> tag to a higher level or incorporate your conditional logic directly into the component. Typically, the former option is recommended:

<AnimatePresence>
    {modalIsVisible && <ModalComponent />}
</AnimatePresence>

(In this scenario, ModalComponent contains the aforementioned code).

Alternatively, you could always render the component and utilize a prop for conditional rendering of its children. However, given that you are dealing with a modal window, this approach may not be suitable.

Answer №2

If you want to achieve this effect, check out more examples here:

  <AnimatePresence>
     <motion.div
        // set initial opacity state
        initial={{ opacity: 0 }}
        // animate component appearance
        animate={{ opacity: 1 }}
        // define transition properties (e.g., duration)
        transition={{ delay: 0.5 }}
        // exit animation setup
        exit={{ opacity: 0 }}
      >
       {your_content_here}
      </motion.div>
  </AnimatePresence>

If you are encountering errors, it may not be related to nextjs. Look for issues within the code/lib of framer

Make sure you avoid typing inside your div like this (?ok 2 exit?):

initial="hidden" exit="pageExit" animate="visible" exit="hidden"

Refer to valid motion components for correct usage. Always consult the official documentation for examples.

P.S. To implement AnimatePresence on multiple pages, wrap your parent component or place the code inside your _app.js. Note that this approach loads AnimatePresence code for each page using the framer library.

function MyApp({ Component, pageProps }) {
  
  return (
    <AnimatePresence>
     <Component {...pageProps} />
    </AnimatePresence>
  )
  
}

MODIFICATION: Upon reviewing the behavior of AnimatePresence, I realized it was not functioning as expected. Here's an alternative method to achieve similar results, demonstrated in the example below.

//npm install this before: npm i react-intersection-observer
import { useInView } from "react-intersection-observer";

//define controls and inView variables in your hooks section
const controls = useAnimation();
const [ref, inView] = useInView();
useEffect(() => {
  if (inView) {
     controls.start("visible");
  }
  else {
     controls.start("hidden");
  }
}, [controls, inView]);

//implement the component with animations
<motion.div
 style={{marginTop: '1000px', marginBottom: '1000px'}}
 ref={ref}
 animate={controls}
 initial="hidden"
 transition={{ duration: 2 }}
 variants={{
     visible: { opacity: 1, scale: 1 },
     hidden: { opacity: 0, scale: 0 }
 }}

>
   <img src="https://super-monitoring.com/blog/wp-content/uploads/2020/03/framer.png"></img>
</motion.div>

I did not utilize AnimationPresence for various reasons. The issue with AnimationPresence lies in its limited ability to accurately track user position on the page. This is why the isVisible variable was introduced in framer examples. By utilizing react-intersection-observer, we can effectively detect user location. Apologies for any confusion prior to the modification.

P.S. Refer to this link for additional information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve the values of a select element from LEVEL 4 within the form submission of LEVEL 3?

To enhance readability, the intricate code has been abstracted. Within our Angular 2 project, we are working with a component called <top-component> (LEVEL 1): <top-component> </top-component> This component includes a template known a ...

Difficulty parsing JSON in MVC .Net Core Controller

I am dealing with a Web Application built in ASP.Net Core 5 that communicates with a Web API in .Net Core. The data returned from the API in JSON format needs to be read from a file named landing.js. Despite the data being stored in the variable (data), I ...

Challenges with Scope in Using AJAX Calls within an Infowindow

Could it be a scope issue? Feel free to correct me if I'm mistaken. I've got a for loop that's placing markers on my map. Each marker has a different infowindow that loads content using ajax callbacks. This is a simplified version of the s ...

Develop a personalized conditional rendering directive in Vue.js

I am exploring how to create a custom Vue conditional directive. While I could simply use a global method and call it within a v-if, I prefer the idea of having a dedicated directive for clarity in my code. My objective is to apply this directive to an el ...

Using Selenium in Java to interact with popup elements

Attempting to retrieve and interact with pop-up/alert elements using selenium in Java has been a bit challenging for me. Below is the code snippet I have been working on: import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import ...

Utilize Javascript to load content dynamically while ensuring each page has a distinct link to individual content pages

As a newcomer to web development, I wanted to share my issue in hopes of finding a more efficient solution than what I've been attempting. Recently, I made changes to my website so that content is loaded dynamically using the jQuery load() function. T ...

Setting a default value in Vue props if it doesn't pass validation: A guide

Is it possible to assign a default value to a prop using a validator? For instance, if the current prop does not pass the validator and is less than 3, I would like to automatically set the value to 1. Here's an example: currentStep: { type ...

Error: excessive recursion detected in <div ng-view="" class="ng-scope">

I've recently started learning angularJS and I've encountered an error that I need help with. Below is my index.html file: <body ng-app="myApp"> <div ng-view></div> <a href="table">click</a> <script ...

Receiving a "Undefined index" error while passing information to a PHP script via jQuery

I have extensively researched this issue, including reading numerous StackOverflow questions, but I am still unable to find a solution. My problem involves retrieving the 'id' attribute value of an HTML 'a' element with jQuery when the ...

Transforming query language from jQuery to Pure JavaScript

I have the following jQuery code that I am attempting to remove and convert into standard JavaScript: $('.switch').click(()=>{ $([".light [class*='-light']", ".dark [class*='-dark']"]).each((i,ele)=& ...

Ways to target other links exclusively during hover effect on a single link

I've been attempting to shrink all other links when one link is hovered over, but I'm only able to make the links after the hovered one shrink. .navlink { width: 100px; display:inline-block; background-color: red; } .navlink:hover~.navl ...

Activate the jQuery click event by specifying the URL

On my webpage, I have a jQuery click function that loads multiple HTML pages into a specified div. I am looking to set specific URLs that will trigger this event, like test.com#about <script type="text/javascript"> $(document). ...

What is the process for generating an alert box with protractor?

While conducting tests, I am attempting to trigger an alert pop-up box when transitioning my environment from testing to production while running scripts in Protractor. Can someone assist me with this? ...

Encountering a problem with displaying error messages in an empty text field

I am facing an issue with displaying error messages when a text field is left blank. I would like a simple message, such as "can't be empty", to appear below the text field in red color when the user clicks the submit button and leaves multiple fields ...

Looking to incorporate new values without replacing them in react.js and mongoDB

function getFilterQuery() { const completedWorkState = WorkflowStates.findOne({title: 'Completed'}); const inProgressWorkState = WorkflowStates.findOne({title: 'In Progress'}); const identifiedWorkState = WorkflowStates.findOne ...

Is there a way to modify a specific key value in all embedded objects using Mongoose?

I'm currently working on a chat application and I'm facing a challenge with implementing the 'seen' functionality. I need to update all chat messages in the database by setting the 'seen' column to true. Here is the schema st ...

Is there a method to accurately detect the rendering of individual elements within a React Component, rather than the entire component itself?

While it's known that Components rendering can be detected through React's Developer Tool, I came across other methods in this source. However, what I'm specifically interested in is detecting the rendering of individual elements within a Co ...

What is the solution to fixing the EPERM error that occurs while trying to run npx create-next-app@latest?

When I attempted to run the create app for React, I encountered an error that stated "Aborting installation. Unexpected error. Please report it as a bug: [Error: EPERM: operation not permitted, mkdir 'D:\React\vita'] { errno: -4048, cod ...

Issue with applying className to ToggleButton component in React with Material-UI

When utilizing React and Material UI, my goal is to efficiently apply styles to a group of ToggleButtons. At the moment, I am only able to specify the style prop for each individual ToggleButton in order to achieve the desired styling. I am attempting to ...

What types of modifications do ViewChildren and ContentChildren QueryLists keep an eye out for?

Imagine you come across the following lines of code: https://i.stack.imgur.com/7IFx1.png And then, in a different section, you stumble upon this code block: https://i.stack.imgur.com/qac0F.png Under what circumstances would () => {} be executed? Wha ...