Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With React, how can I horizontally scroll to the selected item in a scrollable div?

The idea is to have a horizontal scrollable list, and when selecting an item, the list scrolls to that item, which should make the item centered in the list.

I have tried to create an example using React, but I struggle to calculate the scrollLeft value.

http://jsfiddle.net/remisture/zug42kh8/

const scrollContainer = ReactDOM.findDOMNode(this.scrollRef);
const activeItem = ReactDOM.findDOMNode(this.activeRef);

const scrollRect = scrollContainer.getBoundingClientRect();
const activeRect = activeItem.getBoundingClientRect();
const activeWidth = activeRect.width;
const activeLeft = activeRect.left;
const activeRight = activeRect.right;
const scrollWidth = scrollContainer.scrollWidth;
const scrollLeft = scrollRect.left;

scrollContainer.scrollLeft = (scrollWidth / 2) + (activeLeft / 2) + (scrollLeft * 2);

Desired result:

enter image description here

like image 499
Remi Sture Avatar asked Nov 19 '25 20:11

Remi Sture


1 Answers

JSFiddle

First of all, yeah, calculating:

scrollLeftPosition: activeRect.left - scrollRect.left - (scrollRect.width / 2) + (activeRect.width / 2)

Second. I changed manipulation with scrollLeft to "+=". As you should not just assign in your case, but take in account current scroll state.

scrollContainer.scrollLeft += this.state.scrollLeftPosition;

And the main point: you called this.centerActiveItem() before new state applied. this.setState is async function. You need to pass function to call it after updating state.

this.setState({}, callback);
like image 190
Anarion Avatar answered Nov 22 '25 08:11

Anarion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!