React native flatlist

React native flatlist DEFAULT

A deep dive into React Native FlatList

Consider a situation where you want to display a list of items from an API. For example, the Coffee API’s response looks like this:

Coffee API List Response

One possible way to display this to the client is to use the method on this array like so:

const data = getDataFromAPI(); return ( <View style={styles.container}> {data && ( <View> <Text> Your data has loaded! Here is the result:</Text> {data.map((item) => ( <Text key={item.id}> {item.name}</Text> ))} </View> )} </View> );

Here, we are using conditional rendering to check if the data has loaded. If true, we will notify the user and display the list on the screen.
This will be the output:

Coffee API Data Loaded but List is Not Visible

The code should work. So why isn’t our list visible?

This is where comes in to mitigate this problem. It is a React Native component that allows you to render lists with zero hassle and minimal code.

syntax

uses the following syntax:

import { FlatList } from "react-native"; <FlatList data={ //the array to render } keyExtractor={ // Extract keys for each item in the array } renderItem={ //each item from the array will be rendered here } />;
  • In the prop, you will enter the array that you want to display. This can be JSON data from an API
  • The prop will retrieve a unique key for each item in the array
    N.B., if your array contains a or field, you don’t need to include this prop. By default, will look for the or property.
  • will tell React Native how to render the items from the list

Sample usage

Now that we’ve covered the syntax, let’s use it to render our list:

//the data array contains our array of items. const data = [{id:1, title:"Black", description:""},... ]; const Item = ({ title, description }) => ( <View> <Text style={styles.title}>{title} </Text> <Text>{description} </Text> </View> ); const renderItem = ({ item }) => ( <Item title={item.title} description={item.description} /> ); return ( <View style={styles.container}> {data && ( <FlatList data={data} renderItem={renderItem} keyExtractor={(item) => item.id} /> )} </View> );

Let’s deconstruct this code piece by piece:

  • The component will accept two props: and . This component will display them to the UI
  • The function will render the component for every item in the array. As a result, this will display the and fields from each object
  • Moreover, the prop tells React Native that it should use the field as a key
  • In the end, we used conditional rendering to render the data with the React Native element

Sample FlatList with Coffee API

Displaying data from an API

In the real world, React Native developers might have to deal with rendering API data into lists.

In the code below, we are fetching data from the Coffee API and plugging it into our FlatList component:

export default function App() { const [data, setData] = useState(null); const getData = async () => { const resp = await fetch("https://api.sampleapis.com/coffee/hot"); const data = await resp.json(); setData(data); }; //on first mount, fetch data. useEffect(() => { getData(); }, []); const Item = ({ title, description, index }) => ( <View> <Text style={styles.title}> {index}. {title} </Text> <Text> {description} </Text> </View> ); const renderItem = ({ item, index }) => ( <Item description={item.description} title={item.title} index={index} /> ); return ( <View style={styles.container}> {data && ( <FlatList data={data} renderItem={renderItem} /> )} </View> ); }

A few inferences from this code:

  • When the component is first rendered, React invokes the method. This will make a request to the API
  • In the function, we are also using the argument. This is the index corresponding to the current item in the array
  • Notice that we aren’t using the prop. This is because an field is already present, so will use this as the key

RN FlatList Displaying Data from an API

customization

Header component

FlatList also has support for header components. This can be handy in cases where you want to display a search bar on the top of an inventory of contacts.
The prop can help you do that:

import { Divider } from "react-native-elements"; const header = () => { return ( <View> <Text style={styles.title}> Coffee list</Text> <Divider orientation="vertical" /> </View> ); }; return ( <View style={styles.container}> {data && ( <FlatList ListHeaderComponent={header} data={data} renderItem={renderItem} /> )} </View> );

In the above block of code, we first created a function and then passed it into our prop. This will output a simple and component at the top of the component.

FlatList Header Component

Footer component

Consider a situation where the user has scrolled all the way down and wants to go back up. Here, it would be sensible to show a button that would take the client back up automatically. In this case, you could append a footer component for your list. This will indicate that the list has concluded.

You can do it via the prop like so:

//This will be our footer component const endComponent = () => { return ( <View> <Divider orientation="vertical" /> <Text style={styles.text}> List ended</Text> </View> ); }; return ( <View style={styles.container}> {data && ( <FlatList ListFooterComponent={endComponent} data={data} renderItem={renderItem} /> )} </View> );

FlatList Footer Component

Separators

Separator components help the user distinguish each element in the list. This contributes to a better user experience and interface.

To achieve this, use the prop like so:

const separator = () => { return <Divider orientation="vertical" />; }; return ( <View style={styles.container}> {data && ( <FlatList ItemSeparatorComponent={separator} data={data} renderItem={renderItem} /> )} </View> );

RN FlatList Separators

Handling empty lists

Let’s say that you have built a note-taking app in React Native. If the user has no records, it would be suitable to show a “No notes found” message.

For this, the prop is useful:

const data = []; //empty array const handleEmpty = () => { return <Text style={styles.title}> No data present!</Text>; }; return ( <View style={styles.container}> {!data && <Text> Loading</Text>} {data && ( <FlatList ListEmptyComponent={handleEmpty} data={data} renderItem={renderItem} /> )} </View> );

RN FlatList Empty List

navigation methods

also includes a few utility functions for scroll-related operations.

Scroll to end

Assume that you have a list containing hundreds of items. Here, it would be good to display a button that lets the user go all the way down. This will result in a better user experience since the user doesn’t have to manually scroll to the bottom, thus saving time.

To make this possible, you can use the method like so:

const list = useRef(null); const press = () => { list.current.scrollToEnd({ animated: true }); }; const header = () => { return <Button onPress={() => press()} title="Go to end" />; }; return ( <View style={styles.container}> {!data && <Text> Loading</Text>} {data && ( <FlatList ref={list} ListHeaderComponent={header} data={data} renderItem={renderItem} /> )} </View> );

In this piece of code, we created a Hook which will grant us access to ’s utility functions. When the user clicks on the element, the app will execute the method.

FlatList Scroll to End Button

Navigating to a specific index item

We can even scroll to a specific item by calling the method like so:

const list = useRef(null); const press = () => { //scroll to the 12th item in the index. list.current.scrollToIndex({ animated: true, index: 12 }); }; const header = () => { return <Button onPress={() => press()} title="Go to 12th index" />; }; return ( <View style={styles.container}> {!data && <Text> Loading</Text>} {data && ( <FlatList ref={list} ListHeaderComponent={header} data={data} renderItem={renderItem} /> )} </View> );

In this code snippet, we told React that if the user clicks on the button, then it should redirect the user to the twelfth item in the array.

Navigating to a Specific Index

Best practices

Avoid anonymous functions

Try to avoid using anonymous functions in your . The React Native team suggests this so that the function won’t recreate itself every time your list is displayed. This saves memory and CPU resources:

//correct way: no anonymous functions const renderItem = ({ item, index }) => ( <Text> {index}. {item.title} </Text> ); { data && ( <FlatList data={data} keyExtractor={(item) => item.id} renderItem={renderItem} /> ); } //the wrong way. Steer clear from this: { data && ( <FlatList data={data} keyExtractor={(item) => item.id} renderItem={({ item, index }) => ( <Text> {index}.{item.title} </Text> )} /> ); }

Lighter components

The heavier your components are, the more memory they take. Display as little information as you can on your list item. As a bonus, this makes your UI look cleaner.

Even if you do have items that need to display a lot of text, you can use React Navigation. If the user taps on any item, React will direct them to a separate page that will show the remaining details. Here is an example:

RN FlatList with Too Much TextRN FlatList with Read More

Common problems and questions

Images do not render

To solve this problem, check if you are loading images from the local storage or from the network (an API). React Native’s module has a slightly different syntax for each use case.

The code sample below renders images from the file system:

const apiData = [ { id: 1, title: "The Simpsons", year: 1989, image: require("./simpson.jpg"), }, { id: 2, title: "SpongeBob SquarePants ", year: 1999, image: require("./spongebob.jpg"), }, ]; const renderItem = ({ item, index }) => ( <View> <Text style={styles.title}>{item.title} </Text> <Text> {item.year}</Text> <Image style={{ height: 300, width: 300}} source={item.image} resizeMode="contain" /> </View> ); return ( <View style={styles.container}> <FlatList data={apiData} keyExtractor={(item) => item.id.toString()} renderItem={renderItem} /> </View> );

Notice that we are using the method. This tells React Native to fetch images from the local file system.

Render Images with RN FlatList

To display images from the network, use the property for your like so:

const apiData = [ { id: 1, title: "The Simpsons", year: 1989, //url for image image: "https://m.media-amazon.com/images/M/MV5BYjFkMTlkYWU[email protected]@._V1_SY1000_CR0,0,666,1000_AL_.jpg", }, { id: 2, title: "SpongeBob SquarePants ", year: 1999, image: "https://nick.mtvnimages.com/uri/mgid:arc:content:nick.com:9cd2df6e-63c7-43da-8bde-8d77af9169c7?quality=0.7", }, ]; const renderItem = ({ item, index }) => ( <View> <Text style={styles.title}>{item.title} </Text> <Text> {item.year}</Text> <Image style={{ height: 300, width: 300 }} source={{ uri: item.image }} //using uri property resizeMode="contain" /> </View> ); return ( <View style={styles.container}> <FlatList data={apiData} keyExtractor={(item) => item.id.toString()} renderItem={renderItem} /> </View> );

Inverting the list

To reverse the item order, simply use the prop:

return ( <View style={styles.container}> <FlatList data={apiData} keyExtractor={(item) => item.id} renderItem={renderItem} inverted //reverses the list /> </View> );

The list should re-render when a variable changes

To solve this issue, use the prop. This will tell to render whenever the chosen variable updates:

var changedData = 0; //other logic-related code.. return ( <View style={styles.container}> <FlatList data={apiData} extraData={changedData} keyExtractor={(item) => item.id} renderItem={renderItem} /> </View> );

This will now tell React Native to listen for changes in the variable. When a change is detected, React will re-render the list.

Performance issues when rendering a large number of items

You can use the prop. This specifies the number of items rendered per batch, which is the next group of items displayed on every scroll:

return ( <FlatList data={data} extraData={changedData} keyExtractor={(item) => item.id} renderItem={renderItem} maxToRenderPerBatch={5} //render only 5 items per scroll. )

Why not use a instead?

The component renders all the items in one go. This might be fine for small lists, but not for lists with hundreds of items.

For example, take a note-taking app. If your app renders the components and views them all at once, this will result in increased memory usage.

The module handles things differently. It will only render items when they are about to appear and deletes them when they are off view. This results in lower memory usage.

In short, uses lazy loading, which is better for optimization purposes.

Conclusion

In this article, we covered React Native’s usage, its useful functions and customization options. It is a crucial component if you want to render lists in your React Native app. It is an absolute breeze to use and is rock solid.

Thank you for reading! Happy coding.

LogRocket: Full visibility into your web apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

Try it for free.
Sours: https://blog.logrocket.com/deep-dive-react-native-flatlist/

React Native FlatList

next →← prev

The FlatList component displays the similar structured data in a scrollable list. It works well for large lists of data where the number of list items might change over time. The FlatList shows only those renders elements which are currently displaying on the screen, not all the elements of the list at once.

The FlatList component takes two required props: data and renderItem.

The data is the source of elements for the list, and renderItem takes one item from the source and returns a formatted component to render.

To implement the FlatList component, we need to import FlatList from 'react-native' library.

React Native FlatList Example

In this example, we provide hardcoded elements to data prop. Each element in the data props is rendered as a Text component.

The ItemSeparatorComponent prop of FlatList is used to implement the separator between the elements of the list. To perform the click event on list items, we use onPress prop to Text.

Output:

React Native FlatListReact Native FlatList

Next TopicReact Native SectionList



← prevnext →



Sours: https://www.javatpoint.com/react-native-flatlist
  1. Dramatic 2 minute monologues
  2. Yellowstone jamie dutton
  3. Razer synapse beta
  4. Best friend chords

FlatList

A performant interface for rendering basic, flat lists, supporting the most handy features:

  • Fully cross-platform.
  • Optional horizontal mode.
  • Configurable viewability callbacks.
  • Header support.
  • Footer support.
  • Separator support.
  • Pull to Refresh.
  • Scroll loading.
  • ScrollToIndex support.
  • Multiple column support.

If you need section support, use .

Example#

To render multiple columns, use the prop. Using this approach instead of a layout can prevent conflicts with the item height logic.

More complex, selectable example below.

  • By passing to we make sure itself will re-render when the state changes. Without setting this prop, would not know it needs to re-render any items because it is a and the prop comparison will not show any changes.
  • tells the list to use the s for the react keys instead of the default property.

This is a convenience wrapper around , and thus inherits its props (as well as those of ) that aren't explicitly listed here, along with the following caveats:

  • Internal state is not preserved when content scrolls out of the render window. Make sure all your data is captured in the item data or external stores like Flux, Redux, or Relay.
  • This is a which means that it will not re-render if remain shallow-equal. Make sure that everything your function depends on is passed as a prop (e.g. ) that is not after updates, otherwise your UI may not update on changes. This includes the prop and parent component state.
  • In order to constrain memory and enable smooth scrolling, content is rendered asynchronously offscreen. This means it's possible to scroll faster than the fill rate and momentarily see blank content. This is a tradeoff that can be adjusted to suit the needs of each application, and we are working on improving it behind the scenes.
  • By default, the list looks for a prop on each item and uses that for the React key. Alternatively, you can provide a custom prop.

Props#

ScrollView Props#

Inherits ScrollView Props, unless it is nested in another FlatList of same orientation.


Required

#

Takes an item from and renders it into the list.

Provides additional metadata like if you need it, as well as a more generic function which let you set whatever props you want to change the rendering of either the leading separator or trailing separator in case the more common and (which set the prop) are insufficient for your use case.

  • (Object): The item from being rendered.
  • (number): The index corresponding to this item in the array.
  • (Object)
    • (Function)
    • (Function)
    • (Function)
      • (enum('leading', 'trailing'))
      • (Object)

Example usage:


Required

#

For simplicity, data is a plain array. If you want to use something else, like an immutable list, use the underlying directly.


#

Rendered in between each item, but not at the top or bottom. By default, and props are provided. provides / which will update the prop, but you can also add custom props with .


#

Rendered when the list is empty. Can be a React Component (e.g. ), or a React element (e.g. ).


#

Rendered at the bottom of all the items. Can be a React Component (e.g. ), or a React element (e.g. ).


#

Styling for internal View for .


#

Rendered at the top of all the items. Can be a React Component (e.g. ), or a React element (e.g. ).


#

Styling for internal View for .


#

Optional custom style for multi-item rows generated when .


#

A marker property for telling the list to re-render (since it implements ). If any of your , Header, Footer, etc. functions depend on anything outside of the prop, stick it here and treat it immutably.


#

is an optional optimization that allows skipping the measurement of dynamic content if you know the size (height or width) of items ahead of time. is efficient if you have fixed size items, for example:

Adding can be a great performance boost for lists of several hundred items. Remember to include separator length (height or width) in your offset calculation if you specify .


#

If , renders items next to each other horizontally instead of stacked vertically.


#

How many items to render in the initial batch. This should be enough to fill the screen but not much more. Note these items will never be unmounted as part of the windowed rendering in order to improve perceived performance of scroll-to-top actions.


#

Instead of starting at the top with the first item, start at . This disables the "scroll to top" optimization that keeps the first items always rendered and immediately renders the items starting at this initial index. Requires to be implemented.


#

Reverses the direction of scroll. Uses scale transforms of .


#

Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks , then , and then falls back to using the index, like React does.


#

Multiple columns can only be rendered with and will zig-zag like a layout. Items should all be the same height - masonry layouts are not supported.


#

Called once when the scroll position gets within of the rendered content.


#

How far from the end (in units of visible length of the list) the bottom edge of the list must be from the end of the content to trigger the callback. Thus a value of 0.5 will trigger when the end of the content is within half the visible length of the list.


#

If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the prop correctly.


#

Called when the viewability of rows changes, as defined by the prop.

Type
(callback: { changed: array of ViewTokens, viewableItems: array of ViewTokens }) => void

#

Set this when offset is needed for the loading indicator to show correctly.


#

Set this true while waiting for new data from a refresh.


#

This may improve scroll performance for large lists. On Android the default value is .

Note: May have bugs (missing content) in some circumstances - use at your own risk.


#

See for flow type and further documentation.

takes a type an object with following properties

PropertyType
minimumViewTimenumber
viewAreaCoveragePercentThresholdnumber
itemVisiblePercentThresholdnumber
waitForInteractionboolean

At least one of the or is required. This needs to be done in the to avoid following error (ref):

minimumViewTime#

Minimum amount of time (in milliseconds) that an item must be physically viewable before the viewability callback will be fired. A high number means that scrolling through content without stopping will not mark the content as viewable.

viewAreaCoveragePercentThreshold#

Percent of viewport that must be covered for a partially occluded item to count as "viewable", 0-100. Fully visible items are always considered viewable. A value of 0 means that a single pixel in the viewport makes the item viewable, and a value of 100 means that an item must be either entirely visible or cover the entire viewport to count as viewable.

itemVisiblePercentThreshold#

Similar to , but considers the percent of the item that is visible, rather than the fraction of the viewable area it covers.

waitForInteraction#

Nothing is considered viewable until the user scrolls or is called after render.


#

List of / pairs. A specific will be called when its corresponding 's conditions are met. See for flow type and further documentation.

Type
array of ViewabilityConfigCallbackPair

Methods#

#

Displays the scroll indicators momentarily.


#

Provides a reference to the underlying scroll component


#

Provides a handle to the underlying scroll responder.


#

Provides a handle to the underlying scroll node.


#

Tells the list an interaction has occurred, which should trigger viewability calculations, e.g. if is true and the user has not scrolled. This is typically called by taps on items or by navigation actions.


#

Scrolls to the end of the content. May be janky without prop.

Parameters:

Valid keys are:

  • 'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to .

#

Scrolls to the item at the specified index such that it is positioned in the viewable area such that 0 places it at the top, 1 at the bottom, and 0.5 centered in the middle.

Note: Cannot scroll to locations outside the render window without specifying the prop.

Parameters:

NameType
params

Required

object

Valid keys are:

  • 'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to .
  • 'index' (number) - The index to scroll to. Required.
  • 'viewOffset' (number) - A fixed number of pixels to offset the final target position.
  • 'viewPosition' (number) - A value of places the item specified by index at the top, at the bottom, and centered in the middle.

#

Requires linear scan through data - use instead if possible.

Note: Cannot scroll to locations outside the render window without specifying the prop.

Parameters:

NameType
params

Required

object

Valid keys are:

  • 'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to .
  • 'item' (object) - The item to scroll to. Required.
  • 'viewPosition' (number)

#

Scroll to a specific content pixel offset in the list.

Parameters:

NameType
params

Required

object

Valid keys are:

  • 'offset' (number) - The offset to scroll to. In case of being true, the offset is the x-value, in any other case the offset is the y-value. Required.
  • 'animated' (boolean) - Whether the list should do an animation while scrolling. Defaults to .
Sours: https://reactnative.dev/docs/flatlist
React Native #15: FlatList Grid

How To Use React Native Flatlist

facebooktwitterlinkedin

How many apps have you seen that come with lists in them? That may be To-Do Apps, Apps with notes, Email Apps, social Apps with lists of contacts, users, news, some highly specialized apps for the financial sphere with stock prices and real estate worth value, and so on. 

A list is the most basic and simple component that apps have, it is used almost everywhere in our life. You may make a shopping list when deciding to go to the market. And you likely make it in the notes app as a list. 

JavaScript offers a function to build a list, since React.js is JavaScript-based the way to work with lists is similar. On the other hand, React Native is supposed to render native elements both for Android and iOS, so it has a different way to build lists. The most generic option to display a scrolling list of data in React Native was using . Today two options are available to represent lists of data: and  

React Native accelerates the process of building apps across different platforms, thanks to the possibility of reusing most of the code between them. is a component that looks great both on iOS and Android. Let’s get to know it better.   

Basics of React Native Flatlist

is a component that responsible for the display of a list with similar data objects. The display of every element has an identical format and uses a common stylesheet. The data goes in a structured and scrollable manner. 

FlatList uses component to render elements, however, it comes without pure performance issues of and with some additional features out of the box that allow to build a better UI and make the development process easier. 

The component comes into play when you need to display a long scrollable list of items. 

There are two required props for React Native component – and . 

The prop is the data that is displayed in the component. The type of data can be any from starting an array of numbers to an array filled with JSON objects that you fetched through API. 

The prop is a function that takes every item object from the prop and renders them into the list component. If you want your data to display with special styling, you can do this within the or refer to the method through the prop that creates styling for you (an example: . 

There are a bunch of optional props that can be helpful in development. You can find a full list of them in the official documentation, we mention some of them we are going to use further in the article. 

The list of props :

  • renders an element between each item and serves for visual separation of items in the list. It isn’t rendered at the top and the bottom of the list. 
  • is a function that use unique keys of items from the data to track updates and only re-render the items that have been changed. The is a custom implementation of the filed named key in a data item. It is also used to track the reordering of the items. 
  • is an element that renders at the top of the list. It is mostly used to add a search line at the beginning of the list. 
  • is a component that is rendered at the bottom of the list.  
  • Pull to refresh is implemented by using and props. 
  • Infinite Scroll is implemented by using and props. They allow to render items from the next page in the list and implement lazy loading. 
  • prop sets the initial amount of items to render. It’s used to boost the speed of the first render. 

The alternative for is a component. SectionList has recently appeared and is used to add a list of sections with headings for every group of items in the list. It may be useful only if need headings and items in the list are divided into logical groups, otherwise use .  

Why React Native Flatlist is great?

There are some benefits has:

  • The function renders native blocks exactly for mobile platforms
  • doesn’t require a lot of code. It needs only two props to start and you don’t have to make a fancy style to render the list of items – just use props and you are good to go. 
  • is great for performance especially when you deal with a large array and you don’t know the exact number of the items that will render in one list. Displaying large data sets during one render is bad for performance, and React Native only renders elements that are visible on the screen and only updates items that have been changed.

How to implement React Native FlatList

The full code with the final result you can find here:

Let’s look at how we get that result step by step.

Start with importing all the necessary staff we have mentioned in the previous chapter. We need React and some methods from reactnative

Consider that you have a data array with Marvel heroes, where every hero has its unique serial id (these numbers are just serial keys and doesn’t imply the ranking of heroes). 

That array will become the first required props of the React Native . 

Now, to render the list, we create a component called  and declare a style for our future list so the scroll would not intersect with the future header:

Use FlatList

Then  component from  to display the list of Marvel Heroes. We pass the array of data with Marvel heroes via the prop. And then use prop to render the content. The function gets heroes’ names from the array and renders a list component with all names from our array. To turn that into the life we need to declare a function that would be passed as the second required prop to . 

ItemSeparatorComponent

Add a line between list items to separate them. Use prop to add a line between list items that is a view component with a special ‘separator’ class in the stylesheet.  We also include a new prop in the component called . 

KeyExtractor

There are unique identifiers for every hero within . The IDs must be string type, not number. 

To use them we create a function that extracts a unique key of every element from the array, by which can update these elements most effectively, for example, when you delete one element somewhere in the middle of the list. 

In the component we write an additional line of code that calls props. 

Header

It is a component at the top of the list. The sequence of steps to add a header is the same as adding the separator. 

We define a function that renders the interface of the header we need. And then pass the function for rendering to React Native component as a . Besides this way, you can header by using prop and with the help of the state.  Additionally, in the stylesheet we define two new styles for the whole header and text inside it. 

Footer

To add a footer you need to do the same steps that you made with the header. We add a footer component, write two more classes in the stylesheet for the footer and the text for it, then add our to the component. An alternative to adding the footer is to use . 

Pull to refresh

To add pull to refresh two props are required – and . The first prop is an indicator of the type of boolean that tracks whether the view should be updated or not. is a function responsible for loading new data and updating the items in comes into play when the refreshing prop is set to true. 

To implement the pull to refresh option we need to use the hook and declare the function that updates the state of the component. Then add function in component. 

Examples of React Native FlatLists

Facebook 

React Native Flatlist facebook

Facebook team has developed the React Native, so there is nothing strange they have used this technology in Facebook app development. Facebook is the most popular social network worldwide with 2,7 billion monthly active users. Social networks belong to that type of app where lists are extremely demanded. Since the number of users is very high and the app generates millions of gigabytes of data every month, the app has to perform great to provide fast rendering. And if you are a user of Facebook app you may have noticed that your list of contacts works fast. 

Instagram

React Native Flatlist instagram

Instagram is the most popular photo and video sharing app with 1,2 billion monthly active users. The app was released on market on April 3, 2012, and then Facebook acquired it on April 9 the same year. All further development was carried out by the Facebook team. React Native technology showed its strengths again, so today Instagram has grown to the fifth-biggest social media platform worldwide. It unites people from all over the world from small businesses to big ones, news organizations to cultural institutions, celebrities, photographers, and musicians. 

Facebook Ads Manager

React Native Flatlist facebook ads manager

Facebook Ads manager is a business tool to create Facebook ads and manage them. Since Facebook is the most popular social media platform, it became very huge digital advertising platform. Here Facebook Ads manager comes to play, it allows to manage Facebook and Instagram ads: upload them, set budgets, monitor results. All these opportunities are collected inside a small React Native based app.

Shopify

React Native Flatlist shopify

Shopify is a subscription-based software that allows anyone to set up an online store and sell their products. Shopify is just a store builder or a tool to sell your products with over 1 million Shopify users. The team of developers chose to work with React far away in 2018 when they rewrite their app Arrive and developed Shop App. They continued that acquaintance with React Native and are consistently embedding React Native in their apps. 

Conclusion 

We have built a list of Marvel heroes in this article using React Native Flatlist. If you want to learn more about that component we highly recommend to refer to the official documentation and real examples like the one we made. Hope the article was helpful, thanks for reading.  

Do You Want to Learn More About React Native? Check Our Related Articles:

Sours: https://flatlogic.com/blog/how-to-use-react-native-flatlist/

Native flatlist react

Optimizing Flatlist Configuration

Terms#

  • VirtualizedList: The component behind (React Native's implementation of the concept.)

  • Memory consumption: How much information about your list is being stored in memory, which could lead to an app crash.

  • Responsiveness: Application ability to respond to interactions. Low responsiveness, for instance, is when you touch on a component and it waits a bit to respond, instead of responding immediately as expected.

  • Blank areas: When can't render your items fast enough, you may enter a part of your list with non-rendered components that appear as blank space.

  • Viewport: The visible area of content that is rendered to pixels.

  • Window: The area in which items should be mounted, which is generally much larger than the viewport.

Props#

Here are a list of props that can help to improve performance:

removeClippedSubviews#

If , views that are outside of the viewport are detached from the native view hierarchy.

Pros: This reduces time spent on the main thread, and thus reduces the risk of dropped frames, by excluding views outside of the viewport from the native rendering and drawing traversals.

Cons: Be aware that this implementation can have bugs, such as missing content (mainly observed on iOS), especially if you are doing complex things with transforms and/or absolute positioning. Also note this does not save significant memory because the views are not deallocated, only detached.

maxToRenderPerBatch#

It is a prop that can be passed through . This controls the amount of items rendered per batch, which is the next chunk of items rendered on every scroll.

Pros: Setting a bigger number means less visual blank areas when scrolling (increases the fill rate).

Cons: More items per batch means longer periods of JavaScript execution potentially blocking other event processing, like presses, hurting responsiveness.

updateCellsBatchingPeriod#

While tells the amount of items rendered per batch, setting tells your the delay in milliseconds between batch renders (how frequently your component will be rendering the windowed items).

Pros: Combining this prop with gives you the power to, for example, render more items in a less frequent batch, or less items in a more frequent batch.

Cons: Less frequent batches may cause blank areas, More frequent batches may cause responsiveness issues.

initialNumToRender#

The initial amount of items to render.

Pros: Define precise number of items that would cover the screen for every device. This can be a big performance boost for the initial render.

Cons: Setting a low may cause blank areas, especially if it's too small to cover the viewport on initial render.

windowSize#

The number passed here is a measurement unit where 1 is equivalent to your viewport height. The default value is 21 (10 viewports above, 10 below, and one in between).

Pros: Bigger will result in less chance of seeing blank space while scrolling. On the other hand, smaller will result in fewer items mounted simultaneously, saving memory.

Cons: For a bigger , you will have more memory consumption. For a lower , you will have a bigger chance of seeing blank areas.

List items#

Below are some tips about list item components. They are the core of your list, so they need to be fast.

Use basic components#

The more complex your components are, the slower they will render. Try to avoid a lot of logic and nesting in your list items. If you are reusing this list item component a lot in your app, create a component only for your big lists and make them with as little logic and nesting as possible.

Use light components#

The heavier your components are, the slower they render. Avoid heavy images (use a cropped version or thumbnail for list items, as small as possible). Talk to your design team, use as little effects and interactions and information as possible in your list. Show them in your item's detail.

Use shouldComponentUpdate#

Implement update verification to your components. React's implement a with shallow comparison. This is expensive here because it needs to check all your props. If you want a good bit-level performance, create the strictest rules for your list item components, checking only props that could potentially change. If your list is basic enough, you could even use

Use cached optimized images#

You can use the community packages (such as react-native-fast-image from @DylanVann) for more performant images. Every image in your list is a instance. The faster it reaches the hook, the faster your JavaScript thread will be free again.

Use getItemLayout#

If all your list item components have the same height (or width, for a horizontal list), providing the getItemLayout prop removes the need for your to manage async layout calculations. This is a very desirable optimization technique.

If your components have dynamic size and you really need performance, consider asking your design team if they may think of a redesign in order to perform better.

Use keyExtractor or key#

You can set the to your component. This prop is used for caching and as the React to track item re-ordering.

You can also use a prop in your item component.

Avoid anonymous function on renderItem#

Move out the function to the outside of render function, so it won't recreate itself each time render function called.

Sours: https://reactnative.dev/docs/optimizing-flatlist-configuration
React Native FlatList Tutorial - React Native For Absolute Beginners

Hair, on a fast-moving hand, on her stomach, on her legs. It was already getting dark outside. Passers-by, wrapping themselves more tightly in their clothes, returned home. I sat in a cafe by the window and waited for you. To be honest, at the very thought of your appearance, my trousers became cramped.

Similar news:

So, five minutes later, suddenly there was a crackling noise, something fell. Anton turned on the light, it turned out that the fabric of the clamshell was completely torn and the clamshell folded (probably still the first China). Anton put down the cot and wanted to make a bed on the floor, but I know what kind of draft is there. So I told him to lie down on the sofa with me.



887 888 889 890 891