How to use the react-spring.useSprings function in react-spring

To help you get started, we’ve selected a few react-spring examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github react-spring / react-spring-examples / demos / hooks / draggable-list / index.js View on Github external
export default function DraggableList({
  items = 'Lorem ipsum dolor sit'.split(' '),
}) {
  const order = useRef(items.map((_, index) => index)) // Store indicies as a local ref, this represents the item order
  const [springs, setSprings] = useSprings(items.length, fn(order.current)) // Create springs, each corresponds to an item, controlling its transform, scale, etc.
  const bind = useDrag(({ args: [originalIndex], down, movement: [, y] }) => {
    const curIndex = order.current.indexOf(originalIndex)
    const curRow = clamp(
      Math.round((curIndex * 100 + y) / 100),
      0,
      items.length - 1
    )
    const newOrder = swap(order.current, curIndex, curRow)
    setSprings(fn(newOrder, down, originalIndex, curIndex, y)) // Feed springs new style data, they'll animate the view without causing a single render
    if (!down) order.current = newOrder
  })
  return (
    <div style="{{">
      {springs.map(({ zIndex, shadow, y, scale }, i) =&gt; (</div>
github pylnata / teddy / src / features / Puzzle / components / DraggableList.js View on Github external
export default ({ items, setCompleted, img }) => {
  const order = useRef(items.map((_, index) => index)); // Store indicies as a local ref, this represents the item order
  const [springs, setSprings] = useSprings(items.length, fn(order.current)); // Create springs, each corresponds to an item, controlling its transform, scale, etc.
  const bind = useGesture(vars => {
    const {
      args: [originalIndex],
      down,
      delta: [, y]
    } = vars;
    const curIndex = order.current.indexOf(originalIndex);
    const curRow = clamp(
      Math.round((curIndex * temp + y) / temp),
      0,
      items.length - 1
    );
    const newOrder = swap(order.current, curIndex, curRow);
    setSprings(fn(newOrder, down, originalIndex, curIndex, y)); // Feed springs new style data, they'll animate the view without causing a single render
    if (!down) order.current = newOrder;
github bmcmahen / react-gesture-stack / src / Stack.tsx View on Github external
disableNav,
  disableScroll = true,
  navHeight = 50,
  items,
  onIndexChange,
  ...other
}) => {
  const ref = React.useRef(null);
  const count = items.length;
  const bounds = useMeasure(ref);
  const [dragging, setDragging] = React.useState(false);

  useScrollLock(dragging && disableScroll);

  // set default positions
  const [springs, set] = useSprings(count, i => {
    return getAnimationValues(i, index);
  });

  React.useEffect(() => {
    set(i => getAnimationValues(i, index));
  }, [index, set]);

  // handle termination / gesture end
  // either return to current position or
  // animate to the previous index.
  function onEnd({ delta, velocity, direction }: StateType) {
    const { width } = bounds;
    const [x] = delta;
    const xp = (x / width) * 100;

    setDragging(false);
github elixir-europe / BioHackathon-projects-2019 / projects / 29 / src / client / src / components / QuackQuinder / QuackQuinder.js View on Github external
function QuackQuinder({results}) {
    const {state, dispatch} = useContext(QuackContext);
    const {happy, sad} = state;
    const [gone] = useState(() =&gt; new Set()) // The set flags all the results that are flicked out
    const [props, set] = useSprings(results.length, i =&gt; ({...to(i), from: from(i)})) // Create a bunch of springs using the helpers above
    // Create a gesture, we're interested in down-state, delta (current-pos - click-pos), direction and velocity
    const bind = useDrag(({args: [index], down, movement: [mx], distance, direction: [xDir], velocity}) =&gt; {
        const trigger = velocity &gt; 0.2 // If you flick hard enough it should trigger the card to fly out
        const dir = xDir &lt; 0 ? -1 : xDir &gt; 0 ? 1 : 0 // Direction should either point left or right

        if (down) dispatch({type: 'SET_VOTESTATE', data: dir})
        if (!down) dispatch({type: 'SET_VOTESTATE', data: 0})

        if (!down &amp;&amp; trigger) {
            gone.add(index)
            if (dir == 1) {
                dispatch({type: 'ADD_HAPPY', data: results[index]})
            } else {
                dispatch({type: 'ADD_SAD', data: results[index]})
            }
github react-spring / react-spring-examples / demos / hooks / sorted-clicks / index.js View on Github external
export default function App() {
  const [counts, setCounts] = useState(() =&gt; items.map(() =&gt; 0))

  // The ordered item indices
  const order = items.map((_, i) =&gt; i).sort((a, b) =&gt; counts[b] - counts[a])

  // The animated Y-positions
  const springs = useSprings(
    items.length,
    items.map((_, i) =&gt; ({
      y: order.indexOf(i) * (itemSize + itemMargin),
    }))
  )

  return (
    <div>
      
      {springs.map(({ y }, i) =&gt; (
         {
            setCounts(counts =&gt; {
              counts = [...counts]
              counts[i]++</div>
github react-spring / react-spring-examples / demos / hooks / draggable-list / index.js View on Github external
export default function DraggableList({
  items = ['Lorem', 'Ipsum', 'Dolor', 'Sit'],
}) {
  // Store indicies as a local ref, this represents the item order
  const order = useRef([0, 1, 2, 3])
  // Create springs, each corresponds to an item, controlling its transform, scale, etc.
  const [springs, setSprings] = useSprings(items.length, fn(order.current))

  // Preps a gesture handler which returns drag-deltas, touched/clicked state, etc.
  const bind = useGesture(({ args: [originalIndex], down, delta: [, y] }) => {
    // Bunch of math to calculate current row and new order, it's unavoidable ¯\_(ツ)_/¯
    const curIndex = order.current.indexOf(originalIndex)
    const curRow = clamp(
      Math.round((curIndex * 60 + y) / 60),
      0,
      items.length - 1
    )
    const newOrder = swap(order.current.slice(0), curIndex, curRow)
    // Feed springs new style data, they'll animate the view without causing a single render
    setSprings(fn(newOrder, down, originalIndex, curIndex, y))
    if (!down) order.current = newOrder
  })
  // Map resulting animated values to the actual items
github dbismut / react-soft-slider / src / index.js View on Github external
const observer = useRef(null)
  if (!observer.current) observer.current = new IntersectionObserver(cb)

  // we add the slides to the IntersectionObserver:
  // this is recomputed everytime the user adds or removes a slide
  useEffect(() => {
    Array.from(root.current.children).forEach(t => observer.current.observe(t))
  }, [children.length, root])

  // removing the observer on unmount
  useEffect(() => () => observer.current.disconnect(), [])

  // setting the springs with initial position set to restPos:
  // this is important when adding slides since changing children
  // length recomputes useSprings
  const [springs, set] = useSprings(children.length, (i, ctrl) => {
    if (i === 0) instances.current = []
    instances.current.push(ctrl)

    // zIndex will make sure the dragged slide stays on top of the others
    return {
      x: vertical ? 0 : restPos.current,
      y: vertical ? restPos.current : 0,
      s: 1,
      zIndex: 0,
      immediate: key => key === 'zIndex'
    }
  })

  // everytime the index changes, we should calculate the right position
  // of the slide so that its centered: this is recomputed everytime
  // the index changes
github AndreasFaust / react-sled / dist / index.es.js View on Github external
if (i === children.length - 1) {
            dispatch({
              type: 'SET_PAUSE',
              pause: false
            });
            dispatch({
              type: 'SET_RESTED_INDEX'
            });
            callback(immediate, onAnimationEnd);
          }
        }
      };
    });
  }

  var _useSprings = useSprings(children.length, function (i) {
    return {
      x: i * width,
      sc: 1,
      immediate: true,
      config: config,
      cursor: 'auto',
      onStart: function onStart() {
        if (i === children.length - 1) {
          dispatch({
            type: 'SET_PAUSE',
            pause: true
          });
        }
      },
      onRest: function onRest() {
        if (i === children.length - 1) {
github MarcinMiler / tinder-clone / packages / web / src / Pages / Discover / Components / Cards / index.tsx View on Github external
export const Cards: React.FC = ({ users, like, dislike }) =&gt; {
    //@ts-ignore
    const [props, set] = useSprings(users.length, (i: any) =&gt; ({
        to: to(),
        from: from()
    }))

    const bind = useGesture(
        ({
            args: [index],
            down,
            delta: [xDelta],
            direction: [xDir],
            velocity
        }) =&gt; {
            let isGone = false
            const trigger = velocity &gt; 0.2
            const dir = xDir &lt; 0 ? -1 : 1
github AndreasFaust / react-sled / src / sled / springs.js View on Github external
onAnimationStart,
  onAnimationEnd,
  onSledEnd,
  children
}) => {
  const [{
    currentIndex,
    prevIndex,
    viewCount,
    width,
    height,
    dragging,
    config
  }, dispatch] = useStateContext()

  const [props, set] = useSprings(children.length, i => ({
    x: (i - currentIndex) * width,
    sc: 1,
    config,
    cursor: 'auto',
  }))

  const prevWidth = usePrevious(width)
  const prevHeight = usePrevious(height)

  useEffect(() => {
    set(() => ({
      cursor: dragging ? 'grab' : 'auto'
    }))
  }, [dragging, set])

  useEffect(() => {