Seeking assistance in developing a draggable slider using TypeScript. I have managed to retrieve the client and scroll positions, but I am struggling to change the ref scrollLeft position. There are no errors thrown; however, the ref's scrollLeft property remains unchanged.
I attempted logging the ref property that provides the div ref, yet the scrollLeft position consistently shows as 0.
import React, { useRef, useState } from "react";
import Nav from "./Nav";
const Services: React.FC = () => {
const ref = useRef<HTMLDivElement | null>(null);
const [state, setState] = useState({
isDown: false,
clientX: 0,
scrollX: 0,
});
const onMouseDown = (e: React.MouseEvent<HTMLDivElement>): void => {
e.persist();
setState({
...state, isDown: true,
clientX: e.clientX,
});
};
const onMouseUp = () => {
setState({ ...state, isDown: false });
};
const onMouseLeave = () => {
setState({ ...state, isDown: false });
};
const onMouseMove = (e: React.MouseEvent<HTMLDivElement>): void => {
e.persist();
if (!state.isDown) { return; }
const { clientX, scrollX } = state;
if (ref.current) {
// console.log(ref.current.scrollLeft);
ref.current.scrollLeft = scrollX + e.clientX - clientX;
console.log(ref.current.scrollLeft, scrollX + e.clientX - clientX);
// state.scrollX = scrollX + e.clientX - clientX;
// state.clientX = e.clientX;
}
};
return (
<main>
<Nav/>
<div id="content">
<div className="draggable-slider" ref={ref}
onMouseDown={onMouseDown}
onMouseUp={onMouseUp}
onMouseLeave={onMouseLeave}
onMouseMove={onMouseMove}>
<div className="slide">
<h3>.01</h3>
<h3>Basic</h3>
<div className="slide-image">1</div>
</div>
<div className="slide">
<h3>.02</h3>
<h3>Basic</h3>
<div className="slide-image">2</div>
</div>
<div className="slide">
<h3>.03</h3>
<h3>Basic</h3>
<div className="slide-image">3</div>
</div>
<div className="slide">
<h3>.04</h3>
<h3>Basic</h3>
<div className="slide-image">4</div>
</div>
</div>
</div>
</main>
);
};
export default Services;
The CSS
.draggable-slider {
position: relative;
display: grid;
padding: 1rem;
width: 100%;
grid-template-columns: repeat(4, 400px);
grid-column-gap: 3em;
top: 35vh;
user-select: none;
background-color: red;
.slide {
padding: 10px;
line-height: 1;
// cursor: grab;
// &.is-grabbing{
// cursor: grabbing;
// }
Desiring the ability to establish the draggable slide by altering the div scrollLeft position.