Accordion

default

active

1. HTML 마크업 설계

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<button class="accordion">Section 1</button>
<div class="panel">
<p>Lorem ipsum...</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
<p>Lorem ipsum...</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel">
<p>Lorem ipsum...</p>
</div>

2. CSS 스타일링

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
text-align: left;
border: none;
outline: none;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */
.accordion:hover {
background-color: #ccc;
}

/* Style the accordion panel. Note: hidden by default */
.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: max-height 0.4s ease-out;
}

.active {
max-height: 100vh;
}

3. React 로직

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Accordion.jsx
import { useState } from "react";
import "./styles/main.css";

function Accordion({ title, info }) {
const [showInfo, setShowInfo] = useState(false);
return (
<>
<button className="accordion" onClick={() => setShowInfo(!showInfo)}>
{title}
</button>
<div className={`panel ${showInfo ? "active" : ""}`}>
<p>{info}</p>
</div>
</>
);
}

export default Accordion;