Estoy tratando de hacer un carrusel de varias columnas en React (4 columnas) que funcione de manera receptiva (todavía se desplaza en 4 cuando está en una tableta o computadora de escritorio). Cuando hace clic en las flechas, quiero que se deslice por 4 para que se muestren los siguientes 4 elementos. Por el momento, mi cuenta de clics no se actualiza a tiempo para configurar scrollTo en la forma correcta. Además, he tenido problemas al cambiar el tamaño de mi pantalla (a veces salta un elemento o va demasiado lejos). Por cierto, cada artículo tiene un ancho del 25%.
Esto es lo que tengo hasta ahora a continuación:
const [clickCount, setClickCount] = useState(0) const scrollSlide = (direction: 'next' | 'prev') => { const width = mainWrap.current?.clientWidth if (direction === 'next') { setClickCount(clickCount + 1) scrollTo = width * clickCount } else { setClickCount(prevState => prevState - 1) scrollTo = scrollTo - width } containerRef.current?.scrollTo({ behaviour: 'smooth', left: scrollTo }) } return ( <div ref={mainWrap}> <button onClick={() => scrollSllides('prev')}>Prev</button> <button onClick={() => scrollSllides('next')}>Next</button> <div ref={containerRef}> {items?.map((item, index) => ( <ItemComponent key={index} title={item.title} image={item.image} /> ))} </div> </div> )Acabo de definir este control deslizante, según el código que proporciona: https://codesandbox.io/s/epic-feynman-jvt1q?file=/src/styles.css
const Slider = ({ items }) => { const [clickCount, setClickCount] = React.useState(0); const mainWrap = React.useRef(); const containerRef = React.useRef(); const scrollSllides = (direction) => { const width = mainWrap.current?.clientWidth; let scrollTo; const diff = direction === "next" ? 1 : -1; const newValue = (clickCount + diff) % (items.length / 4); setClickCount(newValue); scrollTo = width * newValue; containerRef.current?.scrollTo({ behavior: "smooth", left: scrollTo }); }; return ( <div ref={mainWrap}> <button onClick={() => scrollSllides("prev")}>Prev</button> <button onClick={() => scrollSllides("next")}>Next</button> <div className="Slider" ref={containerRef}> {items?.map((item, index) => ( <ItemComponent key={index} title={item.title} image={item.image} /> ))} </div> </div> ); };Con el siguiente CSS:
.Slider { width: 100%; height: 100px; overflow: scroll; white-space: nowrap; } .ItemComponent { display: inline-block; width: 25%; height: 100px; }