0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】アコーディオンリストの作成

Last updated at Posted at 2023-07-26

はじめに

Reactで簡単なアコーディオンリストを作成するための実装例を紹介します。

作るもの

以下の画像のような、ボタンをクリックすると表示、非表示を切り替えることができるようなUIです。

スクリーンショット 2023-07-26 22.37.25.png

実装

・以下のコマンドで、Reactの雛形を作成する。

terminal
npx create-react-app プロジェクト名

・作成されたApp.js、App.cssファイルを以下のように置き換える。

App.jsimport { useState } from 'react';
import './App.css';

function App() {
  const [selected, setSelected] = useState(null)

  const toggle = (i) => {
    if (selected === i) {
      return setSelected(null)
    }
    setSelected(i)
  } 

  return (
    <div className="wrapper">
      <div className="accordion">
        {data.map((item, i) => 
          <div className="item">
            <div className='title' onClick={() => toggle(i)}>         
              <h2>{item.question}</h2>
              {/* 表示、非表示を切り替えるボタン */}
              <span>{selected === i ? "-" : "+"}</span>
            </div>
            <div 
              className={
                selected === i ? "content show" : "content"
              }
            >
              {item.answer}</div>
          </div>
        )}
      </div>
    </div>
  );
}

// サンプルデータ
const data = [
  {
    question: "Question 1",
    answer: 
      "Answer 1"
  },
  {
    question: "Question 2",
    answer:
      "Answer 2"
  },
  {
    question: "Question 3",
    answer:
      "Answer 3."
  },
  {
    question: "Question 4",
    answer:
      "Answer 4"
  },
]

export default App;
App.css
.wrapper {
  display: flex;
  height: 100vh;
  width: 100vw;
  justify-content: center;
  align-items: center;
}

.accordion {
  width: 500px;
}

.item {
  background: #f0ebe1;
  margin-bottom: 5px;
  padding: 10px, 20px;
}

.title {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

.content {
  color: #8b7f75;
  max-height: 0;
  overflow: hidden;
  transition: all 0.5s cubic-bezier(0.1, 0.1);
}

.content.show {
  height: auto;
  max-height: 9999px;
  transition: all 0.5s cubic-bezier(1.0, 1.0);
}

・以下のコマンドでサーバーを起動する。

terminal
npm start

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?