Motion playing twice in react custom modal hook

33 Views Asked by At

I'm creating a custom modal hook for my web application and animate it using framer motion. Unfortunately even when I'm using key, the animation plays as soon as I change props for the children components of the modal.

import React, { useState } from "react";

import { motion } from "framer-motion";

const useModal = (modalClassName) => {
  const [isOpen, setIsOpen] = useState(false);

  const openModal = async () => {
    setIsOpen(true);
  };

  const closeModal = async () => {
    setIsOpen(false);
  };

  const Modal = ({ children, size }) => {
    return (
      <motion.div
        key="modal-overlay"
        initial={{ opacity: 0 }}
        animate={isOpen ? { opacity: 1, display: "block" } : {}}
        exit={{ opacity: 0 }}
        className="modal-overlay"
      >
        <motion.div
          key="modal-window"
          className={`modal modal-${size}`}
          initial={{ opacity: 0 }}
          animate={isOpen ? { opacity: 1, display: "block" } : {}}
          exit={{ opacity: 0 }}
        >
          {children}
          <button onClick={closeModal}>Close</button>
        </motion.div>
      </motion.div>
    );
  };

  return { Modal, openModal, closeModal };
};

export default useModal;
  • Tried adding ref to the motion.divs
  • Tried using useAnimate() to control the animation
0

There are 0 best solutions below