reactjshoverframer-motion

How to disactivate framer-motion whileHover when button is disabled?


I have an item count component with 2 buttons and I want to disable the whileHover effect when the buttons are disabled. Is it possible?

<div className="flex space-x-5">
    <motion.button
      whileHover={{ scale: 1.1 }}
      transition={{ type: "spring", stiffness: 100, duration: 0.2 }}
      onClick={decrement}
      className="bg-blue-600 px-4 rounded-lg enabled:hover:bg-blue-500 disabled:opacity-60 disabled:cursor-not-allowed text-white"
      disabled={!stock || count <= 1}
    >
      -
    </motion.button>
    <span>{count}</span>
    <motion.button
      whileHover={{ scale: 1.1 }}
      transition={{ type: "spring", stiffness: 100, duration: 0.2 }}
      onClick={increment}
      className="bg-blue-600 px-4 rounded-lg enabled:hover:bg-blue-500 disabled:opacity-60 disabled:cursor-not-allowed text-white"
      disabled={!stock}
    >
      +
    </motion.button>
</div>

Solution

  • You can try to add disabled states and use them to condition the effect:

    const isDisableDecrement = !stock || count <= 1
    const isDisableIncrement = !stock
        
    <div className="flex space-x-5">
            <motion.button
              whileHover={{ scale: isDisableDecrement ? 1 : 1.1 }}
              transition={{ type: "spring", stiffness: 100, duration: 0.2 }}
              onClick={decrement}
              className="bg-blue-600 px-4 rounded-lg enabled:hover:bg-blue-500 disabled:opacity-60 disabled:cursor-not-allowed text-white"
              disabled={isDisableDecrement}
            >
              -
            </motion.button>
            <span>{count}</span>
            <motion.button
              whileHover={{ scale: isDisableIncrement ? 1 : 1.1 }}
              transition={{ type: "spring", stiffness: 100, duration: 0.2 }}
              onClick={increment}
              className="bg-blue-600 px-4 rounded-lg enabled:hover:bg-blue-500 disabled:opacity-60 disabled:cursor-not-allowed text-white"
              disabled={isDisableIncrement}
            >
              +
            </motion.button>
    </div>