<div id='root'></div>
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 300px;
height: 400px;
display: flex;
overflow-x: scroll;
}
.container::scrollbar {
display: none;
}
.container-slider {
display: flex;
}
.box-1 {
background-color: red;
width: 300px;
height: 300px;
}
.box-2 {
background-color: blue;
width: 300px;
height: 300px;
}
.box-3 {
background-color: green;
width: 300px;
height: 300px;
}
.box-4 {
background-color: yellow;
width: 300px;
height: 300px;
}
.tools {
position: absolute;
top: 65%;
left: 50%;
transform: translate(-50%);
display: flex;
}
.tools > button {
margin: 0 1rem;
border: none;
padding: 0.5rem 1rem;
border-radius: 20px;
background-color: #2437e1;
color: white;
}
.tools > button:active {
opacity: 0.8;
}
const { useState, useRef } = React;
function App() {
const sliderRef = useRef();
const [currentIndex, setCurrentIndex] = useState(0);
const totalBoxes = 4;
const moveLeft = () => {
if (currentIndex > 0) {
sliderRef.current.scroll({
left: sliderRef.current.scrollLeft - 300,
behavior: 'smooth'
});
setCurrentIndex(currentIndex - 1);
}
}
const moveRight = () => {
if (currentIndex < totalBoxes - 1) {
sliderRef.current.scroll({
left: sliderRef.current.scrollLeft + 300,
behavior: 'smooth'
});
setCurrentIndex(currentIndex + 1);
}
}
return (
<div>
<div className="container" ref={sliderRef}>
<div className="container-slider">
<div className="box-1"></div>
<div className="box-2"></div>
<div className="box-3"></div>
<div className="box-4"></div>
</div>
</div>
<div className='tools'>
<button onClick={moveLeft}>왼쪽</button>
<div>{currentIndex + 1} / {totalBoxes}</div>
<button onClick={moveRight}>오른쪽</button>
</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
View Compiled
This Pen doesn't use any external CSS resources.