What is the best way to horizontally scroll to a selected item within a scrollable div using React?

I'm working on a project that involves creating a horizontal scrollable list. The goal is to have the list automatically scroll to the selected item, centering it in the view.

While attempting to implement this feature using React, I've encountered difficulties in calculating the scrollLeft value.

You can view my example code here: 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);

Here is the desired result I am aiming for:

https://i.sstatic.net/o5UZo.png

Answer №1

JSFiddle

Initially, the calculation goes like this:

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

Next, I made a change to the scrollLeft manipulation, using "+=" instead of simply assigning a value. It's essential to consider the current scroll position.

scrollContainer.scrollLeft += this.state.scrollLeftPosition;

Lastly, it's crucial to call this.centerActiveItem() after the new state has been applied. Since this.setState is an asynchronous function, you should provide a callback function to execute after the state update.

this.setState({}, callback);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Click event in jQuery triggers element movement

I'm having a tough time figuring this out. I initially thought it was the negative margin causing the issue, but even after removing it, the problem persists. Check out the link below to see what I mean when you click on one of the list items at the ...

Issue with Vuex store not being updated when called from promise resolution

I am facing an issue with my Vue.js application where I have an array called items bound to a Vuex data store and exposed as a computed property using the mapGetters helper. In the created() hook of the component, I make a REST API call to update this arra ...

Distributing JWT to the recipient using Express

Allow me to provide you with an overview of my application, which is quite straightforward. The main concept revolves around a user inputting their accountname and password into an html form on the /Login page like so: <form action="/Login" m ...

In JavaScript/jQuery, there is a technique for retrieving the values of dynamically generated td attributes and the id tags of elements inside them within tr

I am currently working on creating a calendar of events using PHP, jQuery, and ajax. The calendar is embedded within an HTML table, where the rows and fields are dynamically generated based on the number of days in a specific month. In order to successfull ...

Iterating through every image displayed on a webpage

Two inquiries: What is the best way to efficiently loop through every image on a specific webpage and open each one in a new browser tab? Similar concept, but instead of opening in a new tab, I am interested in substituting different images for the ...

Sending an array as JSON data to PHP using the $.ajax post method. The $_POST array is

After spending a considerable amount of time on this, I'm still struggling to figure out what I'm doing wrong. I'm having difficulty retrieving the data in the PHP file. I've made multiple calls to "copy" to populate the "result" arr ...

Question about React.js: What is the best way to add multiple classes to a component by using a ternary operator?

I am looking to apply multiple classes to a component by utilizing a ternary operator. In our shared ts theme file, we have the general button styles defined, but for this specific component, I want to adjust the sizes based on screen width. To achieve thi ...

Having trouble with npm start causing webpack issues?

I have a small React mini app that I am trying to start with the command npm start - package.json - "scripts": { "start": "node server.js" Everything works fine on Windows, but when I try to start it on Ubuntu, the console throws an error. /var/www/r ...

What is the best way to retrieve a PDF file from another website and showcase it on our own site without any redirection?

Is there a way to display a pdf from another website without having to redirect to that site? I'm looking for a solution that involves using the URL directly. ...

What is the best way to organize an array based on string, numerical, and date properties in a reactjs application

I have created a project where I need to sort by date, title, and number, but for some reason, none of them are working and there are no bug notifications. I am not sure how to go about debugging this issue. Any help would be greatly appreciated. Thank you ...

Tips for sharing posts and photos using FB.api platform

Can anyone help with my code for posting feed and photos within FB.api? var requestData = { message : data1, access_token: response.authResponse.accessToken, link : 'http://jonmosley.co.uk', description : 'Descriptionhdofh o ...

Add some pizzazz to your design using jQuery!

I have been working on a web application using asp.net c#. I have a div element where I applied the following style to it at the server side: spanNivelRiesgo1.Attributes.Add("style", "display:none; visibility:hidden"); Now, I have a radiobutton list and ...

Express JS causing NodeJS error | "Issue with setting headers: Unable to set headers after they have been sent to the client"

As I embark on my journey to learn the fundamentals of API development, I am following a tutorial on YouTube by Ania Kubow. The tutorial utilizes three JavaScript libraries: ExpressJS, Cheerio, and Axios. While I have been able to grasp the concepts being ...

What is the best way to locate the nearest marker using the Google Maps Direction Service?

Currently, I am engaged in the development of a Google Maps project where I am integrating markers retrieved from a database onto the map using the drawMarkers function. In addition to this, the Google Maps feature tracks your current location and refreshe ...

Utilizing Next.js with a unique custom Node.js backend implementation

I have successfully developed the frontend using Next.js in order to utilize SSR and enhance SEO. Additionally, I have a personalized NodeJS+express server for managing users and other database tasks (tested thoroughly with Postman). My next step is to in ...

Steps for designing a movable image

I'm looking to implement a feature where the user can drag and drop an image anywhere on the page. Once the user places the image, its position will be saved so that when they revisit the page, it will be in the same location. Thank you! ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

There is no XHR request sent when invoking the http function

I am facing challenges in configuring a service in angular2 to interact with a REST backend. My attempt at setting up a basic example for sending requests to a rest backend and handling the response seems to be on track. The Service is being called correc ...

Issues with CSS causing image resizing problems on Chrome, looking for solutions

On my website, I have favicons from various external domains. However, there seems to be an issue with resizing them when they are not 16px in size. Sometimes only the top or bottom half of the image is displayed, but upon refreshing the page, the entire i ...

Using the express.Router instance for handling errors can be a useful tool in your development

Based on the documentation, it states that any nodejs express middleware function has the capability of being swapped out by App or Router instances: Given that router and app adhere to the middleware interface, they can be used just like any other midd ...