### Install RecyclerListView
Source: https://github.com/flipkart/recyclerlistview/blob/master/README.md
Installs the RecyclerListView package using npm. Supports installing the latest beta version.
```bash
npm install --save recyclerlistview
For latest beta:
`npm install --save recyclerlistview@beta`
```
--------------------------------
### RecyclerListView Usage
Source: https://github.com/flipkart/recyclerlistview/blob/master/docs/guides/samplecode/README.md
Demonstrates the basic usage of the RecyclerListView component with layoutProvider, dataProvider, and rowRenderer props. This is a core example for rendering lists.
```javascript
return ;
```
--------------------------------
### rowRenderer Usage
Source: https://github.com/flipkart/recyclerlistview/blob/master/docs/guides/performance/README.md
Demonstrates the correct way to define `rowRenderer` and highlights the importance of not including a `key` prop to maintain view recycling and prevent performance issues.
```js
rowRenderer(type, data) => {
return ;
}
```
--------------------------------
### RecyclerListView Basic Usage
Source: https://github.com/flipkart/recyclerlistview/blob/master/docs/guides/samplecode/README.md
Demonstrates the basic setup and usage of the RecyclerListView component in a React Native application. It covers initializing the DataProvider, LayoutProvider, and rowRenderer, and rendering a list with different item types.
```javascript
/***
Use this component inside your React Native Application.
A scrollable list with different item type
*/
import React, { Component } from "react";
import { View, Text, Dimensions } from "react-native";
import { RecyclerListView, DataProvider, LayoutProvider } from "recyclerlistview";
const ViewTypes = {
FULL: 0,
HALF_LEFT: 1,
HALF_RIGHT: 2
};
let containerCount = 0;
class CellContainer extends React.Component {
constructor(args) {
super(args);
this._containerId = containerCount++;
}
render() {
return {this.props.children}Cell Id: {this._containerId};
}
}
/***
* To test out just copy this component and render in you root component
*/
export default class RecycleTestComponent extends React.Component {
constructor(args) {
super(args);
let { width } = Dimensions.get("window");
//Create the data provider and provide method which takes in two rows of data and return if those two are different or not.
//THIS IS VERY IMPORTANT, FORGET PERFORMANCE IF THIS IS MESSED UP
let dataProvider = new DataProvider((r1, r2) => {
return r1 !== r2;
});
//Create the layout provider
//First method: Given an index return the type of item e.g ListItemType1, ListItemType2 in case you have variety of items in your list/grid
//Second: Given a type and object set the exact height and width for that type on given object, if you're using non deterministic rendering provide close estimates
//If you need data based check you can access your data provider here
//You'll need data in most cases, we don't provide it by default to enable things like data virtualization in the future
//NOTE: For complex lists LayoutProvider will also be complex it would then make sense to move it to a different file
this._layoutProvider = new LayoutProvider(
index => {
if (index % 3 === 0) {
return ViewTypes.FULL;
} else if (index % 3 === 1) {
return ViewTypes.HALF_LEFT;
} else {
return ViewTypes.HALF_RIGHT;
}
},
(type, dim) => {
switch (type) {
case ViewTypes.HALF_LEFT:
dim.width = width / 2;
dim.height = 160;
break;
case ViewTypes.HALF_RIGHT:
dim.width = width / 2;
dim.height = 160;
break;
case ViewTypes.FULL:
dim.width = width;
dim.height = 140;
break;
default:
dim.width = 0;
dim.height = 0;
}
}
);
this._rowRenderer = this._rowRenderer.bind(this);
//Since component should always render once data has changed, make data provider part of the state
this.state = {
dataProvider: dataProvider.cloneWithRows(this._generateArray(300))
};
}
_generateArray(n) {
let arr = new Array(n);
for (let i = 0; i < n; i++) {
arr[i] = i;
}
return arr;
}
//Given type and data return the view component
_rowRenderer(type, data) {
//You can return any view here, CellContainer has no special significance
switch (type) {
case ViewTypes.HALF_LEFT:
return (
Data: {data}
);
case ViewTypes.HALF_RIGHT:
return (
Data: {data}
);
case ViewTypes.FULL:
return (
Data: {data}
);
default:
return null;
}
}
render() {
return (
);
}
}
const styles = {
container: {
justifyContent: "center",
alignItems: "center",
borderColor: "#000",
borderWidth: 1
},
containerGridLeft: {
justifyContent: "center",
alignItems: "center",
borderColor: "#000",
borderWidth: 1,
marginLeft: 5
},
containerGridRight: {
justifyContent: "center",
alignItems: "center",
borderColor: "#000",
borderWidth: 1,
marginRight: 5
}
};
```
--------------------------------
### extendedState Usage
Source: https://github.com/flipkart/recyclerlistview/blob/master/docs/guides/performance/README.md
Illustrates the correct and incorrect ways to pass the `extendedState` prop to RecyclerListView. The `extendedState` object should only be updated when intended to trigger re-renders, preventing unnecessary component updates.
```js
this.state = {
extendedState: {
ids: [] //array of ids
}
}
//CORRECT
//INCORRECT
```
--------------------------------
### RecyclerListView with RefreshControl
Source: https://github.com/flipkart/recyclerlistview/blob/master/README.md
Demonstrates how to integrate the RefreshControl component with RecyclerListView for pull-to-refresh functionality. This example shows how to pass ScrollView props, including the refreshControl, via the scrollViewProps prop to ensure proper TypeScript compatibility.
```javascript
{
this.setState({ loading: true });
analytics.logEvent('Event_Stagg_pull_to_refresh');
await refetchQueue();
this.setState({ loading: false });
}}
/>
)
}}
/>
```
--------------------------------
### RecyclerListView Ref Handling for Sticky Items
Source: https://github.com/flipkart/recyclerlistview/blob/master/docs/guides/sticky/README.md
When using sticky items with RecyclerListView, it's crucial to pass the ref as a function to the component. This allows the StickyContainer to properly access and manage the RecyclerListView instance. Failure to do so will result in an error.
```javascript
_setRef(recycler) {
this._recyclerRef = recycler;
}
```
--------------------------------
### rowHasChanged Implementation
Source: https://github.com/flipkart/recyclerlistview/blob/master/docs/guides/performance/README.md
The `rowHasChanged` method is crucial for RecyclerListView to detect data changes and optimize rendering by skipping unchanged rows. Incorrect implementation can lead to performance degradation.
```js
this.state = {
dataProvider: new DataProvider((r1, r2)=> {
//This is the important part
return r1 !== r2;
})
}
```
--------------------------------
### Apply Window Correction in RecyclerListView
Source: https://github.com/flipkart/recyclerlistview/blob/master/docs/guides/sticky/README.md
Demonstrates how to use the `applyWindowCorrection` method to adjust `startCorrection` and `endCorrection` for sticky elements. This method is invoked upon scrolling and receives current offsets and the `windowCorrection` object. The `windowCorrection` object's properties can be modified to influence the perceived viewability of items.
```javascript
/**
* this method is invoked upon scrolling the recyclerlistview, and provides current X offset, Y offset and WindowCorrection object.
* WindowCorrection has 3 params that can be used to change the perceived viewability of items present.
*
* The value of startCorrection and endCorrection is provided to StickyContainer upon scroll.
* current offset can be used to dynamically calculate the correctional offset to be provided.
*
* @param {current X offset value} offsetX
* @param {current Y offset value} offsetY
* @param {*} windowCorrection
*/
_applyWindowCorrection(offset, offsetY, windowCorrection) {
// Provide a positive value to startCorrection to shift the Top Sticky widget downwards.
windowCorrection.startCorrection = -20;
// Provide a positive value to endCorrection to shift the Bottom Sticky widget upwards.
windowCorrection.endCorrection = 20;
}
render() {
return (
);
}
```
--------------------------------
### renderAheadOffset Usage in RecyclerListView
Source: https://github.com/flipkart/recyclerlistview/blob/master/docs/guides/performance/README.md
The `renderAheadOffset` property in RecyclerListView controls the buffer size for rendering items ahead of the current scroll position. This helps prevent visible blank spaces during scrolling. It's recommended to use the smallest value that eliminates blank spaces, as lower values lead to fewer view creations and quicker recycling. Larger values might improve scrolling speed in certain use cases but increase the number of mounted views.
```documentation
renderAheadOffset: Specifies how much ahead of the current scroll position items are rendered to prevent blank spaces. This buffer is maintained on both the top and bottom of the list. Lower values are generally better for performance, ensuring fewer views are created and recycled quickly. Choose the smallest value that provides a smooth scrolling experience without blank spaces. Larger values may improve scrolling speed but increase the number of views mounted.
```
--------------------------------
### RecyclerListView Sticky Sample Implementation
Source: https://github.com/flipkart/recyclerlistview/blob/master/docs/guides/sticky/sample/README.md
This JavaScript code defines a React Native component that utilizes RecyclerListView with sticky headers and footers. It sets up the data provider, layout provider, and custom row rendering logic, including a specific override for a sticky row.
```javascript
import React from 'react';
import {View, Text} from 'react-native';
import {RecyclerListView, DataProvider, LayoutProvider} from 'recyclerlistview';
import StickyContainer from 'recyclerlistview/sticky';
export default class StickySample extends React.Component {
constructor(props) {
super(props);
this._setRef = this._setRef.bind(this);
this._recyclerRef = null;
this.data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 6, 7, 8, 9, 10, 11];
this.dataProvider = new DataProvider((r1, r2) => {
return r1 !== r2;
});
this.dataProvider = this.dataProvider.cloneWithRows(this.data);
this.layoutProvider = new LayoutProvider(
index => {
return index;
},
(type, dimension) => {
dimension.height = 100;
dimension.width = 360;
}
);
}
_rowRenderer = (type, data, index) => {
let color = 'grey';
switch(index%6) {
case 0:
color = "purple";
break;
case 1:
color = "green";
break;
case 2:
color = "blue";
break;
case 3:
color = "red";
break;
case 4:
color = "yellow";
break;
case 5:
color = "orange";
break;
}
return (
{index}
);
};
/**
* This method is called whenever a view has to be stuck as a header or footer.
* Override the views for whichever sticky view requires changes.
* Eg. This can be used to add shadows etc. to the views once they stick.
*/
_overrideRowRenderer = (type, data, index) => {
const view = this._rowRenderer(type, data, index);
switch(index) {
case 7: // Only overriding sticky index 7, sticky indices 3 and 10 will remain as they are.
const color = "cyan";
return (
Overridden sticky
);
break;
}
return view;
};
render() {
return (
);
}
_setRef(recycler) {
this._recyclerRef = recycler;
}
}
```
--------------------------------
### RecyclerListView Props
Source: https://github.com/flipkart/recyclerlistview/blob/master/README.md
This section details the properties that can be passed to the RecyclerListView component to configure its behavior and appearance. These props cover aspects such as data provision, layout definition, rendering logic, scroll event handling, and performance optimizations.
```APIDOC
layoutProvider: BaseLayoutProvider
- Required: Yes
- Description: Constructor function that defines the layout (height / width) of each element.
dataProvider: DataProvider
- Required: Yes
- Description: Constructor function that defines the data for each element.
contextProvider: ContextProvider
- Required: No
- Description: Used to maintain scroll position in case the view gets destroyed, which often happens with back navigation.
rowRenderer: (type: string | number, data: any, index: number) => JSX.Element | JSX.Element[] | null
- Required: Yes
- Description: Method that returns the React component to be rendered. You get the type, data, index, and extendedState of the view in the callback.
initialOffset: number
- Required: No
- Description: Initial offset you want to start rendering from. This is very useful if you want to maintain scroll context across pages.
renderAheadOffset: number
- Required: No
- Description: Specify how many pixels in advance you want views to be rendered. Increasing this value can help reduce blanks (if any). However, keeping this as low as possible should be the intent. Higher values also increase re-render compute.
isHorizontal: boolean
- Required: No
- Description: If true, the list will operate horizontally rather than vertically.
onScroll: (rawEvent: ScrollEvent, offsetX: number, offsetY: number) => void
- Required: No
- Description: On scroll callback function that executes as a user scrolls.
onRecreate: (params: OnRecreateParams) => void
- Required: No
- Description: Callback function that gets executed when recreating the recycler view from the context provider.
externalScrollView: { new (props: ScrollViewDefaultProps): BaseScrollView }
- Required: No
- Description: Use this to pass your own implementation of BaseScrollView.
onEndReached: () => void
- Required: No
- Description: Callback function executed when the end of the view is hit (minus onEndThreshold if defined).
onEndReachedThreshold: number
- Required: No
- Description: Specify how many pixels in advance for the onEndReached callback.
onEndReachedThresholdRelative: number
- Required: No
- Description: Specify 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 onEndReached callback.
onVisibleIndicesChanged: TOnItemStatusChanged
- Required: No
- Description: Provides visible index; helpful in sending impression events.
onVisibleIndexesChanged: TOnItemStatusChanged
- Required: No
- Description: (Deprecated in 2.0 beta) Provides visible index; helpful in sending impression events.
renderFooter: () => JSX.Element | JSX.Element[] | null
- Required: No
- Description: Provide this method if you want to render a footer. Helpful in showing a loader while doing incremental loads.
initialRenderIndex: number
- Required: No
- Description: Specify the initial item index you want rendering to start from. Preferred over initialOffset if both specified.
scrollThrottle: number
- Required: No
- Description: iOS only; Scroll throttle duration.
canChangeSize: boolean
- Required: No
- Description: Specify if size can change.
distanceFromWindow: number
- Required: No
- Description: (Deprecated) Use `applyWindowCorrection()` API with `windowShift`. [Usage?](#applywindowcorrection-usage)
applyWindowCorrection: (offset: number, windowCorrection: WindowCorrection) => void
- Required: No
- Description: (Enhancement/replacement to `distanceFromWindow` API) Allows updation of the visible windowBounds to based on correctional values passed. User can specify **windowShift**; in case entire RecyclerListWindow needs to shift down/up, **startCorrection**; in case when top window bound needs to be shifted for e.x. top window bound to be shifted down is a content overlapping the top edge of RecyclerListView, **endCorrection**: to alter bottom window bound for a similar use-case. [Usage?](#applywindowcorrection-usage)
useWindowScroll: boolean
- Required: No
- Description: Web only; Layout Elements in window instead of a scrollable div.
disableRecycling: boolean
- Required: No
- Description: Turns off recycling.
forceNonDeterministicRendering: boolean
- Required: No
- Description: Default is false; if enabled dimensions provided in layout provider will not be strictly enforced. Use this if item dimensions cannot be accurately determined.
extendedState: object
- Required: No
- Description: In some cases the data passed at row level may not contain all the info that the item depends upon, you can keep all other info outside and pass it down via this prop. Changing this object will cause everything to re-render. Make sure you don't change it often to ensure performance. Re-renders are heavy.
itemAnimator: ItemAnimator
- Required: No
- Description: Enables animating RecyclerListView item cells (shift, add, remove, etc).
style: object
- Required: No
- Description: To pass down style to inner ScrollView.
scrollViewProps: object
- Required: No
- Description: For all props that need to be proxied to inner/external scrollview. Put them in an object and they'll be spread and passed down.
```
--------------------------------
### RecyclerListView Styles
Source: https://github.com/flipkart/recyclerlistview/blob/master/docs/guides/samplecode/README.md
Defines common styles for the RecyclerListView container, including different background colors for various layouts. These styles are typically used within a React Native StyleSheet.
```javascript
const styles = {
container: {
justifyContent: "space-around",
alignItems: "center",
flex: 1,
backgroundColor: "#00a1f1"
},
containerGridLeft: {
justifyContent: "space-around",
alignItems: "center",
flex: 1,
backgroundColor: "#ffbb00"
},
containerGridRight: {
justifyContent: "space-around",
alignItems: "center",
flex: 1,
backgroundColor: "#7cbb00"
}
};
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.