Setting the initial scroll position in a ReactNative ListView after the data has been loaded

I need a solution for jumping to specific dates in an events section, with the initial scroll position set to the first future date.

To achieve this, I have attempted to store the y positions of each date in the state.

renderSectionHeader= (sectionData, sectionID) => (
      <View
        onLayout={(event) => {
          const { y } = event.nativeEvent.layout;
          const sectionPosition = { [sectionID]: y };
          const sectionPositions = Object.assign({}, this.state.sectionPositions, sectionPosition);
          this.setState({ sectionPositions });
        }}
       ...

However, there are issues with lazy rendering and renderSectionHeader not being called for elements further down the list.

Trying to calculate positions mathematically results in sections showing on screen as it moves towards the selected date.

Are there any solutions to address these challenges?

RELATED

React Native ListView: How to scroll to a particular row

https://github.com/facebook/react-native/issues/499

UPDATE

I know that all rows in my app have the same height.

Using contentOffset={{ y: offsetY }} instead of setScroll doesn't work due to needing to render all items up to the given item.

initialListSize={99999999} works but slows down the page significantly, which is discouraged.

UPDATE 2

Is it feasible to provide initial content to the datasource and update data by adding extra items before and after elements on screen?

Alternatively, is there a library that can fulfill these requirements?

Answer №1

FlatList from the experimental folder in the React-Native repository seems to be the solution we've been waiting for.

Check out FlatList on GitHub

A Summary of Better ListView - FlatList: A superior list view implementation designed to address our needs!

Main differences from the current ListView:

  • Virtualization of items to manage memory usage – items outside the visible window are unmounted and memory is released, meaning instance state is not retained when items scroll off-screen.
  • No need for DataSource – a simple data prop with Array<any> shape. By default, items are expected to have a {key: string} structure, but a custom rowExtractor function can be provided for different data shapes, such as mapping id to key. The underlying VirtualizedList provides more flexibility.
  • Advanced scrolling mechanisms: scrollToEnd, scrollToIndex, and scrollToItem, along with the usual scrollToOffset.
  • Built-in pull-to-refresh functionality – utilize the onRefresh and refreshing props.
  • Addition of new rows typically occurs with low priority after interactions/animations finish, unless there's a shortage of rendered content. This should enhance app responsiveness.
  • Component props replace render functions, like
    ItemComponent: ReactClass<{item: Item, index: number}>
    replacing
    renderRow: (...) =>
      React.Element<*>
  • Automatic support for dynamic items using onLayout, or provide getItemLayout for optimized performance and smoother scrolling behaviors like scrollToIndex and scrollbar actions.
  • The visibility callback has been upgraded to a more powerful viewability callback that functions in both vertical and horizontal modes across Android and iOS, possibly other platforms too. Enhanced by the viewablePercentThreshold allowing the client to determine item visibility thresholds.

Demo:

https://i.sstatic.net/t0xhJ.gif

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

Modifying the appearance of Bootstrap button colors

I recently came across this code on the Bootstrap website. I am curious about how to change the text color from blue to black in this specific code snippet. Currently, the text is appearing as blue by default. For reference and a live example, you can vis ...

Guide on showing string array values in an alert popup using JavaScript

I am struggling to display a string array in a JavaScript alert popup. The goal is to show the string index or Serial Number, followed by a space and then a line break before displaying the value of each string in the array. Unfortunately, my current code ...

Utilizing Firebase 9.0.1 Functions in Vue.js 3

As a newcomer to Vue, I decided to tackle my second tutorial which involved integrating Firebase backend with Vue. However, the tutorial was based on Vue 2 and an older version of Firebase. Determined to stay current, I set out to replicate the project usi ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

Progress to the following pages after each page remains inactive for 3 seconds

Is it possible for someone to assist me in creating a script that automatically switches between pages when the page is idle for 3 seconds? My current setup only allows for movement from one page to another, but I have 4 pages that I would like this featur ...

"Troubleshooting ng-submit in AngularJS: How to Fix a Function That

I've encountered an issue with my angular-promise where a http method is not being called when a form is submitted using ng-submit. There are no errors, but it seems like the function is never executed. Here's the JavaScript code snippet: myapp. ...

Does JSON.Stringify() change the value of large numbers?

My WCF service operation returns an object with properties of type long and List<string>. When testing the operation in a WCF application, everything functions correctly and the values are accurate. However, when attempting to call the service using ...

Unable to stop the default action in IE for certain code

I am facing an issue on my website where the JavaScript I have implemented to prevent page reload is not working in Internet Explorer. The code functions properly in all other browsers, except IE. Here is the JavaScript code snippet that should prevent pa ...

The React server-side rendering isn't reflecting changes made on the client-side route

Upon the first refresh, both the server and client side are updated; however, subsequent updates only affect the client side when switching pages with react router. For instance, refreshing the page or entering a new URL causes changes on the server and t ...

How can I stop jQuery mobile from updating the document title?

It appears that jQuery mobile automatically uses the text content of data-role="header" to set the document.title. For example: <div data-position="fixed" data-role="header"> <h1>This text</h1> </div> To work around this, I ha ...

Error: JSON parsing failed due to an unexpected character, resulting in null data

Many people have asked similar questions on the same topic, but I have not been able to find a solution for my specific problem. Below is the code snippet that I am working with: $.post("show_search_results.php", {location_name: ""+location_name+"", key: ...

Exploring ES6: Harnessing the Power of Classes

I am currently learning the ES6 syntax for classes. My background is in C#, so I apologize if my terminology is not accurate or if something seems off. For practice, I am working on building a web app using Node and Express. I have defined some routes as ...

Is there a way for me to retrieve the name of a newly opened browser tab from the original tab?

I have written a code snippet to create a new tab within the same browser by clicking on a link. function newTab() { var form1 = document.createElement("form"); form1.id = "newTab1" form1.method = "GET"; form1.action = "domainname"; //My ...

Discover which sub package is needed by running Npm check

While executing the command npm install, I encountered this error message: The package "getSnapshot-pkg-repo@^1.0.0" required by "conventional-changelog-core@^2.0.11" could not be found on the "npm" registry. I am uncertain about the source of this i ...

Redis VS RabbitMQ: A Comparison of Publish/Subscribe Reliable Messaging

Context I am working on a publish/subscribe application where messages are sent from a publisher to a consumer. The publisher and consumer are located on separate machines, and there may be occasional breaks in the connection between them. Goal The obj ...

Ensure that the array of JSON objects is a subset of another array of JSON objects

I am looking to compare each array in testEdge with newarr and find the matching id for each array in testEdge const testEdge = [ [{ id: '0', from: '0', to: '1' }, { id: '1', from: '1&ap ...

Creating unique random shapes within a larger shape on a canvas, as shown in the image

I have a parent rectangle and would like to add up to 10 or fewer rectangles on the right-hand side corner of the parent rectangle, as shown in the image below: https://i.sstatic.net/RW9ix.png I attempted to write code to achieve this, but the alignment ...

Unable to transmit information back to React

Recently stepping into the world of React and Node.js, I have successfully created a function in my Node.js application that executes a Python script using child process. However, I seem to be facing a challenge with my router post method named pythonExecu ...

AngularJS - Showcase a dynamic list of information according to the value chosen

Seeking assistance from anyone willing. I have data in JSON format structured like this { state1: [ member1, member2], state2: [ member3,member4...], ... } There is a dropdown that displays the states listed in the JSON data. When a state is selected, I ...

Angular 13.0 version is experiencing issues when trying to run the "ng serve" command

After installing the npm module, I encountered a problem while using node.js version 14.17.6. I am a beginner in Angular and struggling to find a solution due to not using the latest Angular CLI version. Any help would be greatly appreciated. Thank you in ...