React.js ライブラリ「react-multi-carousel」を使って軽量なカルーセルを作成する

React.js ライブラリ「react-multi-carousel」を使って軽量なカルーセルを作成する

ライブラリ「react-multi-carousel」をインストールすると、軽量なカルーセルを利用することが可能です。ここでは、react.jsで「react-multi-carousel」を利用するための手順と簡単な使い方を記述してます。

環境

  • OS  Rocky Linux release 8.4 (Green Obsidian)
  • node v14.17.3
  • npm 7.19.1
  • yarn 1.22.10
  • React 17.0.2

react.js環境構築

下記のコマンドで構築してます。ここでは、react-appという名前でプロジェクトを作成してます。

yarn global add create-react-app
npx create-react-app react-app

react-multi-carouselインストール

作成したプロジェクトに移動して、インストールします。

## 作成したプロジェクトに移動
cd react-app
 
## インストール
yarn add react-multi-carousel

react-multi-carousel使い方

srcディレクトリにsample.jsと名前で、以下のコードを記述します。

import React from 'react'
import Carousel from 'react-multi-carousel'
import 'react-multi-carousel/lib/styles.css'

const Sample = () => {

    const responsive = {
        superLargeDesktop: {
            // the naming can be any, depends on you.
            breakpoint: { max: 4000, min: 3000 },
            items: 5
        },
        desktop: {
            breakpoint: { max: 3000, min: 1024 },
            items: 3
        },
        tablet: {
            breakpoint: { max: 1024, min: 464 },
            items: 2
        },
        mobile: {
            breakpoint: { max: 464, min: 0 },
            items: 1
        }
    }

    return (
        <div>
            <Carousel responsive={responsive}>
                <div>Item 1</div>
                <div>Item 2</div>
                <div>Item 3</div>
                <div>Item 4</div>
            </Carousel>
        </div>
    );
};

export default Sample;

次に、srcディレクトリ配下にあるApp.jsを下記のように編集します。

import React from 'react';
import Sample from './sample';
import './App.css';

function App() {
  const style = {
    width: "30%",
    margin: "0 auto",
    marginTop: 250,
  };
  return (
    <div className="App">
      <div style={style}>
        <Sample />
      </div>
    </div>
  );
}

export default App;

実行します。

yarn start

ブラウザから http://プライベートIP:3000にアクセスすると、カルーセルが作成いることが確認できます。