Mastering Framer Motion: Magic with layoutId

Rishabh Bose
··5 min read

The Magic of layoutId

Framer Motion's layoutId allows developers to animate elements between completely different parts of the DOM seamlessly. It's the secret behind many premium UI experiences.

Implementation Strategy

By simply providing a matching string to the layoutId prop on two different motion components, Framer Motion handles the complex FLIP animation under the hood.

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";

export function SharedElementExample() {
  const [selectedId, setSelectedId] = useState(null);

  return (
    <>
      {items.map(item => (
        <motion.div layoutId={item.id} onClick={() => setSelectedId(item.id)}>
          <motion.h5>{item.subtitle}</motion.h5>
          <motion.h2>{item.title}</motion.h2>
        </motion.div>
      ))}

      <AnimatePresence>
        {selectedId && (
          <motion.div layoutId={selectedId}>
            <motion.h5>{item.subtitle}</motion.h5>
            <motion.h2>{item.title}</motion.h2>
            <motion.button onClick={() => setSelectedId(null)}>Close</motion.button>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}