🐙

【Framer Motion】コンポーネントまとめ②

2025/02/15に公開

はじめに

Motionコンポーネントに関する記事はこちら
https://zenn.dev/mof_moriko/articles/f1f787ec5999ce

本記事ではMotionコンポーネント以外をまとめています

Lazy Motion

Motion for Reactのバンドルサイズを削減できるコンポーネント

  1. 基本的な使い方
    mコンポーネントと組み合わせて使用
mコンポーネント

LazyMotionと組み合わせて使用する軽量版のmotionコンポーネント
m.div,m.buttonなどHTML要素に対応したコンポーネントを提供

import { LazyMotion, domAnimations } from "motion/react"
import * as m from "motion/react-m"

export const MyComponent = () => (
  <LazyMotion features={domAnimations}>
    <m.div animate={{ opacity: 1 }} />
  </LazyMotion>
)
  1. メリット
    通常のmotionコンポーネントは34kb,LazyMotionは初期バンドル6kb
    必要な機能だけを動的にロードできる

  2. 機能のロード方法

  • 同期的ロード
    • features={domAnimations}のように指定
  • 非同期ロード
    • dynamic importを使用

LayoutGroup

複数のmotion要素のレイアウトアニメーションを同期させるコンポーネント

  1. 基本的な使い方
  • LayoutGroupで囲む要素にはlayoutプロパティを指定
  • 同期したい要素をLayoutGroupで囲む
import { motion, LayoutGroup } from "motion/react"
import { useState } from "react"

// 個別のアコーディオン項目コンポーネント
function Item({ header, content }) {
  const [isOpen, setIsOpen] = useState(false)
  
  return (
    <motion.div
      layout
      onClick={() => setIsOpen(!isOpen)}
    >
      <motion.h2 layout>{header}</motion.h2>
      {isOpen ? content : null}
    </motion.div>
  )
}

// アコーディオンコンテナ
function Accordion() {
  return (
    <LayoutGroup>
      <Item header="Section 1" content="Content 1" />
      <Item header="Section 2" content="Content 2" /> 
    </LayoutGroup>
  )
}

  1. 使用シーン
    アコーディオンメニュー、タブパネル、グリッドレイアウトの変更など

MotionConfig

子のMotion要素に対してグローバルな設定を提供できるコンポーネント

  1. 基本的な使い方
import { motion, MotionConfig } from "motion/react"

export const MyComponent = ({ isVisible }) => (
  <MotionConfig transition={{ duration: 1 }}>
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
    />
  </MotionConfig>
)

  1. 主なprops
props 特徴
transition すべての子motion要素のデフォルトトランジション設定を定義
個別のmotion要素で上書き可能
reduceMotion アニメーションの縮小設定
user,always,neverの設定値がある
notice Content Security Policyを使用する場合のnonce属性
style要素のセキュリティポリシーに適用

Reorder

ドラッグ&ドロップでリストの並び替えを実装するコンポーネント

  1. 基本的な使い方
import { Reorder } from "motion/react"
import { useState } from "react"

function ReorderList() {
  const [items, setItems] = useState([0, 1, 2, 3])

  return (
    <Reorder.Group axis="y" values={items} onReorder={setItems}>
      {items.map((item) => (
        <Reorder.Item key={item} value={item}>
          {item}
        </Reorder.Item>
      ))}
    </Reorder.Group>
  )
}

  1. コンポーネント構成
  • Reorder.Group
    • 並び替え可能なリストのコンテナ
  • Reorder.Item
    • 個々の並び替え可能なアイテム
  1. 重要なprops
props 特徴
axios 並び替えの方向 ("y" または "x")
values 並び替え対象の配列
onReorder 並び替え時のコールバック関数

Discussion