【Laravelプロジェクト】react-image-galleryを導入

技術構成

Laravel Laravel Framework 10.15.0
React react-dom@18.2.0
DaisyUi daisyui@3.5.0
tailwind @tailwindcss/forms@0.5.4

いい感じなフォトギャラリーないのか

HP作成を行っているとスライダーの要望が度々出てくるはずです。

かくいう僕も今回、そういった要望があってスライダーを導入しなければいけない状態でした。

 

一度、jQueryで生実装したことがあるのですが、なんやかんや面倒くさい思いをした苦い経験があったので、今回は生実装を避けたいという思いからReact でいい感じなライブラリないのか調べたところ「react-image-gallery」に出会いました。

 

天下のReact 様は流石だなと言う感じです。

react-image-gallery以外の選択肢としては以下のようなものが挙げられます。

react-image-gallery https://github.com/xiaolin/react-image-gallery
画像のスライドショーを作成するための高機能なライブラリ
react-images https://github.com/jossmac/react-images
シンプルなカスタマイズ可能なグリッドスタイルのイメージギャラリーを作成するためのライブラリ
react-awesome-lightbox https://github.com/photostory/react-awesome-lightbox
モーダルウィンドウ内で画像を表示するためのライブラリ

 

実際に導入

npm でインストール。

npm install react-image-gallery

 

インポート

import ImageGallery from 'react-image-gallery';
import 'react-image-gallery/styles/css/image-gallery.css';

※2行目のcss もインポートしてください。
 css もインポートすることで梱包されているスタイルを当てることが可能です。

 

上記の設定で使う準備が完了です。

あとは自由に設定していくだけです。

 

今回はLaravel からデータを渡すため、コントローラーから配列を渡します。(本当はModel でデータ定義して渡すべきですが、)

$images = [
            [
                "original" => "/img/AsItFlows/asit_team.jpg",
                "thumbnail" => "/img/AsItFlows/asit_team.jpg",
                "originalAlt" => "チーム",
                "thumbnailAlt" => "チーム",
                "onErrorImageURL" => "/img/AsItFlows/logo.jpg",
            ],
            [
                "original" => "/img/AsItFlows/sunset.jpg",
                "thumbnail" => "/img/AsItFlows/sunset.jpg",
                "originalAlt" => "サンセット",
                "thumbnailAlt" => "サンセット",
                "onErrorImageURL" => "/img/AsItFlows/logo.jpg",
            ],
            [
                "original" => "/img/AsItFlows/surf_member.jpg",
                "thumbnail" => "/img/AsItFlows/surf_member.jpg",
                "originalAlt" => "メンバー",
                "thumbnailAlt" => "メンバー",
                "onErrorImageURL" => "/img/AsItFlows/logo.jpg",
            ],
            ...
        ];
        shuffle($images);
        return Inertia::render('Public/AsItFlows/Top', [
            'items' => $images
        ]);

 

最後にjsx 側でいい感じに使用します。

<ImageGallery items={items}
  showNav={true}
  autoPlay={true}
  showFullscreenButton={false}
  useBrowserFullscreen={false}
  showPlayButton={false}
/>

 

 

んー。素敵。

 

 

Twitterでフォローしよう

読んでみーな
おすすめの記事