Skip to content

Wrong counting for React.Children in TrailingActions  #54

@olegkolt

Description

@olegkolt

Describe the bug
In some cases Full Swipe with ≤2 children cases an error:

_this.trailingFullSwipeAction is not a function
TypeError: _this.trailingFullSwipeAction is not a function
    at SwipeableListItem.eval [as handleDragEnd] (webpack://react-swipeable-list-example/../src/SwipeableListItem.js?:328:19)
    at eval (webpack://react-swipeable-list-example/../src/SwipeableListItem.js?:174:13)

To Reproduce
Create a list of TrailingActions with 'null' as the last child:

<TrailingActions>
  <SwipeAction onClick={handleReject(id)}>
   ...
  </SwipeAction>
  <SwipeAction destructive={true} onClick={handleDelete(id)}>
   ...
  </SwipeAction>
  {null}
</TrailingActions>

Expected behavior
No error for cases if some of TrailingActions's children is not valid React element.

Desktop (please complete the following information):

  • OS: Android, iOS, mac
  • Browser: chrome
  • Version: latest

Additional context
How to fix: count valid react children before maping:

src/TrailingActions.js:
---
if (Array.isArray(children)) {

    let lastValidChildIndex = 0;

    React.Children.forEach(children, (child, index) => {
        if (React.isValidElement(child)) {
            lastValidChildIndex = index;
        }
    });

    return React.Children.map(children, (child, index) => {
      if (!React.isValidElement(child)) {
        return child;
      }
      return React.cloneElement(child, {
        main: index === lastValidChildIndex,
        trailing: true,
      });
    });
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions