Convert Figma logo to code with AI

caseywebdev logoreact-list

:scroll: A versatile infinite scroll React component.

1,961
176
1,961
71

Top Related Projects

33,863

Build forms in React, without the tears 😭

📋 React Hooks for form state management and validation (Web + React Native)

🏁 High performance subscription-based form state management for React

A Higher Order Component using react-redux to keep form state in a Redux store

RxJS middleware for action side effects in Redux using "Epics"

Quick Overview

The react-list project is a lightweight and flexible React component for rendering large lists and grids. It provides a simple and efficient way to handle the rendering of large datasets in a React application, optimizing performance by only rendering the visible items.

Pros

  • Performance Optimization: The react-list component efficiently manages the rendering of large datasets, only rendering the visible items and avoiding unnecessary re-renders.
  • Flexibility: The component can be used to render a variety of list and grid layouts, with customizable item sizes and spacing.
  • Lightweight: The library is relatively small in size, with a focus on simplicity and ease of use.
  • Accessibility: The component includes built-in support for accessibility features, such as keyboard navigation and screen reader compatibility.

Cons

  • Limited Customization: While the component is flexible, the level of customization may be limited compared to building a custom list/grid component from scratch.
  • Dependency on React: The react-list component is tightly coupled with the React library, and may not be suitable for non-React projects.
  • Potential Learning Curve: Developers unfamiliar with the react-list component may need to spend some time understanding its API and usage patterns.
  • Lack of Active Maintenance: The project appears to have limited recent activity, which could be a concern for long-term maintenance and support.

Code Examples

Here are a few examples of how to use the react-list component:

import React from 'react';
import ReactList from 'react-list';

const MyList = () => {
  const items = Array.from({ length: 1000 }, (_, i) => `Item ${i}`);

  return (
    <ReactList
      itemRenderer={(index, key) => <div key={key}>{items[index]}</div>}
      length={items.length}
      type="uniform"
    />
  );
};

This example demonstrates the basic usage of the react-list component, rendering a list of 1000 items.

import React from 'react';
import ReactList from 'react-list';

const MyGrid = () => {
  const items = Array.from({ length: 100 }, (_, i) => `Item ${i}`);

  return (
    <ReactList
      itemRenderer={(index, key) => (
        <div key={key} style={{ width: 100, height: 100 }}>
          {items[index]}
        </div>
      )}
      length={items.length}
      type="grid"
      itemsPerRow={5}
    />
  );
};

This example shows how to use the react-list component to render a grid layout, with 5 items per row.

import React, { useState } from 'react';
import ReactList from 'react-list';

const MyDynamicList = () => {
  const [items, setItems] = useState(Array.from({ length: 100 }, (_, i) => `Item ${i}`));

  const handleAddItem = () => {
    setItems([...items, `New Item ${items.length}`]);
  };

  return (
    <div>
      <button onClick={handleAddItem}>Add Item</button>
      <ReactList
        itemRenderer={(index, key) => <div key={key}>{items[index]}</div>}
        length={items.length}
        type="uniform"
      />
    </div>
  );
};

This example demonstrates how to use the react-list component with a dynamic list of items, allowing the user to add new items to the list.

Getting Started

To get started with the react-list component, follow these steps:

  1. Install the library using npm or yarn:
npm install react-list
  1. Import the ReactList component in your React application:
import ReactList from 'react-list';
  1. Render the ReactList component, passing in the necessary props:
<ReactList
  itemRenderer={(index, key) => <div key={key}>Item {index}</div>}
  length={100}
  type="uniform"

Competitor Comparisons

33,863

Build forms in React, without the tears 😭

Pros of Formik

  • Formik provides a comprehensive set of features for managing form state, validation, and submission, making it a powerful and flexible solution for building complex forms in React applications.
  • Formik's API is well-designed and intuitive, with a focus on developer experience and ease of use.
  • Formik has a large and active community, with extensive documentation and a wealth of third-party integrations and plugins.

Cons of Formik

  • Formik's feature set may be overkill for simple forms, and it may introduce unnecessary complexity in such cases.
  • Formik's learning curve can be steeper than some other form libraries, especially for developers new to React or form management.

Code Comparison

React List

<List>
  <ListItem>Item 1</ListItem>
  <ListItem>Item 2</ListItem>
  <ListItem>Item 3</ListItem>
</List>

Formik

<Formik
  initialValues={{ name: '', email: '' }}
  onSubmit={(values) => console.log(values)}
>
  {(props) => (
    <form onSubmit={props.handleSubmit}>
      <input
        type="text"
        name="name"
        onChange={props.handleChange}
        value={props.values.name}
      />
      <input
        type="email"
        name="email"
        onChange={props.handleChange}
        value={props.values.email}
      />
      <button type="submit">Submit</button>
    </form>
  )}
</Formik>

📋 React Hooks for form state management and validation (Web + React Native)

Pros of react-hook-form/react-hook-form

  • Provides a more comprehensive and feature-rich form management solution compared to React List.
  • Offers advanced validation and error handling capabilities out of the box.
  • Supports a wide range of form input types and integrates well with various UI libraries.

Cons of react-hook-form/react-hook-form

  • Has a steeper learning curve compared to the simpler React List library.
  • May be overkill for smaller, less complex forms where React List could suffice.
  • Requires more boilerplate code to set up and configure compared to React List.

Code Comparison

React List:

const [items, setItems] = useState([]);

const addItem = () => {
  setItems([...items, { id: uuid(), value: '' }]);
};

const removeItem = (index) => {
  const newItems = [...items];
  newItems.splice(index, 1);
  setItems(newItems);
};

react-hook-form/react-hook-form:

const { register, handleSubmit, formState: { errors } } = useForm();

const onSubmit = (data) => {
  console.log(data);
};

return (
  <form onSubmit={handleSubmit(onSubmit)}>
    <input {...register('name', { required: true })} />
    {errors.name && <span>This field is required</span>}
    <button type="submit">Submit</button>
  </form>
);

🏁 High performance subscription-based form state management for React

Pros of React Final Form

  • Flexibility: React Final Form provides a flexible and extensible API, allowing developers to customize the form handling logic to their specific needs.
  • Performance: The library uses a memoization-based approach to optimize performance, reducing unnecessary re-renders and improving the overall user experience.
  • Validation: React Final Form offers a robust validation system, supporting both synchronous and asynchronous validation, as well as custom validation rules.

Cons of React Final Form

  • Complexity: The library has a steeper learning curve compared to React List, as it introduces more concepts and configuration options.
  • Boilerplate: Integrating React Final Form into a project may require more boilerplate code, as developers need to set up the form state management and validation logic.

Code Comparison

React List:

<List
  items={items}
  renderItem={(item) => (
    <div>
      <h3>{item.title}</h3>
      <p>{item.description}</p>
    </div>
  )}
/>

React Final Form:

<Form
  onSubmit={onSubmit}
  validate={validate}
  render={({ handleSubmit }) => (
    <form onSubmit={handleSubmit}>
      <Field name="name" component="input" type="text" />
      <Field name="email" component="input" type="email" />
      <button type="submit">Submit</button>
    </form>
  )}
/>

A Higher Order Component using react-redux to keep form state in a Redux store

Pros of redux-form/redux-form

  • Provides a comprehensive set of features for managing form state in a Redux-based application, including validation, field-level error handling, and support for complex form structures.
  • Integrates well with the Redux ecosystem, allowing for easy integration with other Redux-based libraries and tools.
  • Offers a wide range of customization options, allowing developers to tailor the form behavior to their specific needs.

Cons of redux-form/redux-form

  • Can be more complex to set up and configure compared to simpler form management solutions, especially for smaller or less complex forms.
  • May introduce additional boilerplate code and complexity to the codebase, which can make it harder to maintain for some projects.

Code Comparison

redux-form/redux-form

import { Field, reduxForm } from 'redux-form'

const MyForm = props => {
  const { handleSubmit } = props
  return (
    <form onSubmit={handleSubmit}>
      <Field name="name" component="input" type="text" />
      <button type="submit">Submit</button>
    </form>
  )
}

export default reduxForm({ form: 'myForm' })(MyForm)

caseywebdev/react-list

import React, { useState } from 'react'

const List = () => {
  const [items, setItems] = useState([])
  const [newItem, setNewItem] = useState('')

  const addItem = () => {
    setItems([...items, newItem])
    setNewItem('')
  }
}

RxJS middleware for action side effects in Redux using "Epics"

Pros of redux-observable/redux-observable

  • Asynchronous Side Effects: redux-observable provides a powerful way to handle asynchronous side effects in your Redux application, using RxJS Observables.
  • Testability: The use of Observables makes the code more testable, as you can easily test the individual Epics (the core of redux-observable) in isolation.
  • Flexibility: redux-observable is highly flexible, allowing you to handle a wide range of asynchronous scenarios, from simple AJAX requests to complex, event-driven workflows.

Cons of redux-observable/redux-observable

  • Complexity: The learning curve for redux-observable can be steeper than some other Redux middleware options, as it requires understanding RxJS Observables.
  • Performance: Depending on the complexity of your application and the way you use Observables, redux-observable can potentially have a higher performance overhead compared to simpler Redux middleware.

Code Comparison

React List (caseywebdev/react-list):

const List = ({ items, renderItem }) => (
  <ul>
    {items.map((item, index) => (
      <li key={index}>{renderItem(item)}</li>
    ))}
  </ul>
);

redux-observable (redux-observable/redux-observable):

const fetchUserEpic = (action$, state$) =>
  action$.pipe(
    ofType(FETCH_USER),
    mergeMap(action =>
      ajax.getJSON(`/users/${action.payload.userId}`).pipe(
        map(response => fetchUserSuccess(response)),
        catchError(error => of(fetchUserFailure(error)))
      )
    )
  );

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

ReactList

A versatile infinite scroll React component.

Install

bower install react-list

# or

npm install react-list

ReactList depends on React.

Examples

Check out the example page and the the example page source for examples of different configurations.

Here's another simple example to get you started.

import loadAccount from 'my-account-loader';
import React from 'react';
import ReactList from 'react-list';

class MyComponent extends React.Component {
  state = {
    accounts: []
  };

  componentWillMount() {
    loadAccounts(::this.handleAccounts);
  }

  handleAccounts(accounts) {
    this.setState({accounts});
  }

  renderItem(index, key) {
    return <div key={key}>{this.state.accounts[index].name}</div>;
  }

  render() {
    return (
      <div>
        <h1>Accounts</h1>
        <div style={{overflow: 'auto', maxHeight: 400}}>
          <ReactList
            itemRenderer={::this.renderItem}
            length={this.state.accounts.length}
            type='uniform'
          />
        </div>
      </div>
    );
  }
}

Props

axis (defaults to y)

The axis that this list scrolls on.

initialIndex

An index to scroll to after mounting.

itemRenderer(index, key)

A function that receives an index and a key and returns the content to be rendered for the item at that index.

itemsRenderer(items, ref)

A function that receives the rendered items and a ref. By default this element is just a <div>. Generally it only needs to be overridden for use in a <table> or other special case. NOTE: You must set ref={ref} on the component that contains the items so the correct item sizing calculations can be made.

itemSizeEstimator(index, cache)

A function that receives an item index and the cached known item sizes and returns an estimated size (height for y-axis lists and width for x-axis lists) of that item at that index. This prop is only used when the prop type is set to variable and itemSizeGetter is not defined. Use this property when you can't know the exact size of an item before rendering it, but want it to take up space in the list regardless.

itemSizeGetter(index)

A function that receives an item index and returns the size (height for y-axis lists and width for x-axis lists) of that item at that index. This prop is only used when the prop type is set to variable.

length (defaults to 0)

The number of items in the list.

minSize (defaults to 1)

The minimum number of items to render at any given time. This can be used to render some amount of items initially when rendering HTML on the server.

pageSize (defaults to 10)

The number of items to batch up for new renders. Does not apply to 'uniform' lists as the optimal number of items is calculated automatically.

scrollParentGetter (defaults to finding the nearest scrollable parent)

A function that returns a DOM Element or Window that will be treated as the scrolling container for the list. In most cases this does not need to be set for the list to work as intended. It is exposed as a prop for more complicated uses where the scrolling container may not initially have an overflow property that enables scrolling.

scrollParentViewportSizeGetter (defaults to scrollParent's viewport size)

A function that returns the size of the scrollParent's viewport. Provide this prop if you can efficiently determine your scrollParent's viewport size as it can improve performance.

threshold (defaults to 100)

The number of pixels to buffer at the beginning and end of the rendered list items.

type (one of simple, variable, or uniform, defaults to simple)
  • simple This type is...simple. It will not cache item sizes or remove items that are above the viewport. This type is sufficient for many cases when the only requirement is incremental rendering when scrolling.

  • variable This type is preferred when the sizes of the items in the list vary. Supply the itemSizeGetter when possible so the entire length of the list can be established beforehand. Otherwise, the item sizes will be cached as they are rendered so that items that are above the viewport can be removed as the list is scrolled.

  • uniform This type is preferred when you can guarantee all of your elements will be the same size. The advantage here is that the size of the entire list can be calculated ahead of time and only enough items to fill the viewport ever need to be drawn. The size of the first item will be used to infer the size of every other item. Multiple items per row are also supported with this type.

useStaticSize (defaults to false)

Set to true if the item size will never change (as a result of responsive layout changing or otherwise). This prop is only used when the prop type is set to uniform. This is an opt-in optimization that will cause the very first element's size to be used for all elements for the duration of the component's life.

useTranslate3d (defaults to false)

A boolean to determine whether the translate3d CSS property should be used for positioning instead of the default translate. This can help performance on mobile devices, but is supported by fewer browsers.

Methods

scrollTo(index)

Put the element at index at the top of the viewport. Note that if you aren't using type='uniform' or an itemSizeGetter, you will only be able to scroll to an element that has already been rendered.

scrollAround(index)

Scroll the viewport so that the element at index is visible, but not necessarily at the top. The scrollTo note above also applies to this method.

getVisibleRange() => [firstIndex, lastIndex]

Return the indices of the first and last items that are at all visible in the viewport.

FAQ

What is "ReactList failed to reach a stable state."?

This happens when specifying the uniform type without actually providing uniform size elements. The component attempts to draw only the minimum necessary elements at one time and that minimum element calculation is based off the first element in the list. When the first element does not match the other elements, the calculation will be wrong and the component will never be able to fully resolve the ideal necessary elements.

Why doesn't it work with margins?

The calculations to figure out element positioning and size get significantly more complicated with margins, so they are not supported. Use a transparent border or padding or an element with nested elements to achieve the desired spacing.

Why is there no onScroll event handler?

If you need an onScroll handler, just add the handler to the div wrapping your ReactList component:

<div style={{height: 300, overflow: 'auto'}} onScroll={this.handleScroll}>
  <ReactList ... />
</div>

Development

open docs/index.html
make

NPM DownloadsLast 30 Days