npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-sorta

v0.1.10

Published

#### A simple yet powerful sortable list for React!

Downloads

44

Readme

Sorta

A simple yet powerful sortable list for React!

  • Works automatically either in a vertical or horizontal direction with rtl support.
  • Doesn't affect the DOM tree by itself: no styles are applied, and no elements are created or copied:
    • Provides {x: number; y: number}property for you to decide how to apply styles: transform, margin or left & top.
    • Operates within a single container that keeps you safe with CSS cascade dependencies (.container > .item {...}) that obviously doesn't work with cloning and appending element to document.body.
  • Supports scrollable containers and virtualized lists.

See Demo

Basic usage

npm install react-sorta
yarn add react-sorta

Container

import { useCallback, useState } from "react";
import { Sorta, SortaEvent } from "react-sorta";

const [ list, setList ] = useState([ "Apple", "Banana", "Orange", "Kiwi", "Pear" ])

const onSortEnd = useCallback(({ order, from, to }: SortaEvent) => {
  /**
   order: provides indices of current list in new order
   from: source index
   to: destination index

   EXAMPLE: Move second element to 4th position:
   {
     order: [0,2,3,1,4],
     from: 1,
     to: 3
   }
   **/
  setList(current => order.map(index => current[index]))
}, []);

return <Sorta onSortEnd={onSortEnd}>
  {list.map((label, index) => (
    <Item index={index} key={label}>{label}</Item>
  ))}
</Sorta>

Item

To use sorting item you need only two params:

  • ref passed to HTML element to initialize element bounds.
  • onSortStart event handler passed as onMouseDown/onPointerDown event to start dragging.
  • translate prop to get x,y shift for each element

All three props can be passed to different elements, so you can use one element as a sorting handle, get bounds from another, and move only the third element.

Using with HOC

import { forwardRef, PropsWithChildren } from "react";
import { sortaElement, SortaElementProps } from "react-sorta";

const Item = sortaElement(forwardRef((props: PropsWithChildren<SortaElementProps>, ref) => {
  const { onSortStart, translate: {x, y} } = props;
  return (
    <div
      ref={ref}
      onMouseDown={onSortStart}
      style={{transfrom: `translate(${x}px, ${y}px)`}}
    >
      {props.children}
    </div>
  )
}));

Using with hook

import { useSorta } from "react-sorta";

const Item = (props: PropsWithChildren<{ index: number }>) => {
  const { ref, onSortStart, translate } = useSorta(props.index);
  /*...*/
};

Scroll Container

It's easy to use Sorta within the scrolling container. Just pass RefObject<HTMLElement> to containerRef prop.

const containerRef = useRef<HTMLDivElement | null>(null);

return <div ref={containerRef} style={{overflow: "auto"}}>
  <Sorta onSortEnd={onSortEnd} containerRef={containerRef}>
    {list.map((label, index) => (
      <Item index={index} key={label}>{label}</Item>
    ))}
  </Sorta>
</div>

Note, that containerRef can be used not only for scrolling purposes but to prevent items to be dragged outside the parent container.

Virtualization

Using Sorta with virtualization lists is a bit tricky since the virtualizer skips elements that are out of bounds so with default usage dragging element will eventually disappear on scrolling. To handle that use onItemUnmount prop that passes translate and copy of the dragging element you can append to the container if needed.

Also, you need to provide elements count with count prop

Example with react-window virtualizer:

import { FixedSizeList } from "react-window";
import { Sorta } from "react-sorta";

const containerRef = useRef<HTMLDivElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);

<Sorta
  onSortEnd={setList}
  count={list.length}
  containerRef={containerRef}
  onItemUnmount={(element: HTMLElement, translate: {x: number; y: number}) => {
    element.style.transform = `translate(0, ${translate.y}px)`;
    contentRef.current?.appendChild(element);
  }}>
  <FixedSizeList
    height={300}
    width={200}
    itemSize={50}
    itemCount={list.length}
    outerRef={containerRef}
    innerRef={contentRef}>
    {({ index, style }) => (
      <Item key={list[index]} index={index} style={style}>
        {list[index]}
      </Item>
    )}
  </FixedSizeList>
</Sorta>

Types

SortaProps

Props of Sorta container

| Property | Description | Type | | |:-----------------:|:------------------------------------------------------------------------------------------------------------------------------------|:----------------------------------------------------------------------|:--------:| | onSortEnd | Event fired after finishing sorting. Provides ordered indices of the current list, source and destination indices. | ({ order: number[], from: number; to: number }) => void; | Required | | containerRef | Provides items container. Used to get bounding rect and invoke the '.scrollTo()' method when dragging item. | RefObject<HTMLElement> | Optional | | count | Provides the number of elements in the list in case it's impossible to get this number from children, e.g., using virtualization. | number | Optional | | onItemUnmount | Provides callback if dragging element was unmounted, e.g. in virtualized lists, to manually append it container | (element: HTMLElement, translate: { x: number, y: number }) => void | Optional |

SortaElementProps

Props of sorting element

| Property | Description | Type |
|:---------------:|:---------------------------------------------------------------------------------|:----------------------------------| | index | Index of the current element | number | | ref | Used to identify bounds of sorting elements. | React.ForwardedRef<HTMLElement> | | onSortStart | Provides event handler to pass on element as onMouseDown/onPointerDown event | React.MouseEventHandler | | translate | Provides x,y shift of current element. | { x: number; y: number } | | isDragging | Indicates if current element is currently dragging. | boolean | | isSortable | Indicates if elements are currently sorting except for dragging element. | boolean |