Answer the question
In order to leave comments, you need to log in
Why does useState work weird?
There is a slider with dots and arrows, the code is:
<div className={s.slider}>
<div className={s.slides} ref={slideRef}>
{slides.map((item, index: number) => (
<Slide key={index} />
))}
</div>
<div className={s.slidesDots}>
{dots.map((item: number, index: number) => <div key={index} className={dot === index ? s.DotActive : s.Dot} onClick={() => changeSlide("dot", item, index)} />)}
</div>
<div className={s.arrowLeft} onClick={() => changeSlide("minus")}>
</div>
<div className={s.arrowRight} onClick={() => changeSlide("plus")}>
</div>
</div>
let position: number = 0;
const slideRef = useRef<HTMLHeadingElement | null>(null);
const [dot, setDot] = useState<number>(0);
const changeSlide = (option: string, item?: number, index?: number) => {
if (slideRef && slideRef.current) {
switch (option) {
case "dot":
if (item !== undefined && index !== undefined) {
slideRef.current.style.left = `${position = item}%`;
setDot(index);
}
break;
case "minus":
if (position === 0) {
slideRef.current.style.left = `${position = -400}%`;
// setDot(4);
} else {
slideRef.current.style.left = `${position += 100}%`;
// setDot(dot - 1);
}
break;
case "plus":
if (position === -400) {
slideRef.current.style.left = `${position = 0}%`;
// setDot(0);
} else {
slideRef.current.style.left = `${position -= 100}%`;
setDot(dot + 1 );
}
break;
default:
break;
}
console.log(position, dot);
}
}
Answer the question
In order to leave comments, you need to log in
No need to change the DOM manually. You don't need slideRef and all the sodomy it's involved in.
Make position as state, change piously, and specify style.left depending on it:
<div className={s.slides} style={{left: position + '%'}}>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question