I am trying to scroll an element with mouse drag and I am facing a problem. When I try to change the value of an element’s scrollLeft
property it does not do anything and when I log the value it always stays at 0
.
I even tried to give scrollLeft
a value but it never changes from 0
.
This is the code I am trying to use :
//App.js
import React from 'react';
import Slider from './slider.js';
import './style.css';
export function App(props) {
return (
<div className='App'>
<Slider>
<div className="slide" id="1">Slide 1</div>
<div className="slide" id="2">Slide 2</div>
<div className="slide" id="3">Slide 3</div>
</Slider>
</div>
);
}
//slider.js
import React, { useState, useRef } from 'react';
import './style.css';
const Slider = ({ children }) => {
const [isDragging, setIsDragging] = useState(false);
const [startX, setStartX] = useState(0);
const [scrollLeft, setScrollLeft] = useState(0);
const sliderRef = useRef();
const startDrag = (e) => {
setIsDragging(true);
setStartX(e.pageX - sliderRef.current.offsetLeft);
setScrollLeft(sliderRef.current.scrollLeft);
};
const endDrag = () => {
setIsDragging(false);
};
const onDrag = (e) => {
if (!isDragging) return;
e.preventDefault();
const x = e.pageX - sliderRef.current.offsetLeft;
const walk = (x - startX) * 2;
sliderRef.current.scrollLeft = scrollLeft - walk;//<-Does not do anything
//sliderRef.current.scrollLeft+= 40;//<-Does not do anything too
console.log(sliderRef.current.scrollLeft);//<-Allways outputs 0
};
return (
<div
className="slider"
ref={sliderRef}
onMouseDown={startDrag}
onMouseLeave={endDrag}
onMouseUp={endDrag}
onMouseMove={onDrag}
>
{children}
</div>
);
};
export default Slider;
body {
background: transparent; /* Make it white if you need */
padding: 0 24px;
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.App {
color: #72a24d;
overflow: hidden;
}
.slide {
min-width: 300px;
height: 200px;
margin-right: 10px;
background-color: #ccc;
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
color: #333;
}
.slider {
display: flex;
overflow: hidden;
cursor: grab;
}
.slider:active {
cursor: grabbing;
}
Is there something wrong with the way I set up the code?
I also noticed that if I tried to change the element’s scrollLeft
property via the inspector, the same thing happens : it always stays at 0
even if the code itself does not output any error.