Code Monkey home page Code Monkey logo

react-touch-carousel's Introduction

Node.js CI npm version dependencies Status js-standard-style

react-touch-carousel

Micro carousel framework for React.JS https://xiaody.github.io/react-touch-carousel/docs/

Yes, there are a few carousel libraries out there. Most of them are mature and easy to use for common usage, but none of them are convenient for the highly customized fancy UX that your team's cool designer wants.

react-touch-carousel does it in a different way. Instead of accepting some static DOM nodes and providing a thousand options, it does an inversion of control and lets you decide what content inside carousel are rendered and how they are styled, totally and dynamically.

Installation

To install the stable version:

npm install --save react-touch-carousel

Usage

import TouchCarousel from 'react-touch-carousel'

const listOfData = [
  // your data array here
]

function CarouselContainer (props) {
  // render the carousel structure
}

function renderCard (index, modIndex, cursor) {
  const item = listOfData[modIndex]
  // render the item
}


<TouchCarousel
  component={CarouselContainer}
  cardCount={listOfData.length}
  cardSize={375}
  renderCard={renderCard}
  loop
  autoplay={3000}
/>

The CarouselContainer() and renderCard() are where all the magic happens, which shall be directed by you. See some detailed examples.

Options

props.component {Component}

Your container component of the carousel.

react-touch-carousel will pass it's touch listeners, dragging/active state, current position cursor to this component.

It is actually called like this:

<Component
  cursor={usedCursor}
  carouselState={carouselState}
  onTouchStart={onTouchStart}
  onTouchMove={onTouchMove}
  onTouchEnd={onTouchEnd}
  onTouchCancel={onTouchCancel}
>
  {allYourRenderedCards}
</Component>

props.renderCard(index, modIndex, cursor, carouselState) {Function}

The card renderer.

All rendered cards joined as an array will be passed to props.component as it's children.

props.cardCount {Number}

The count of your cards, not including the padded ones.

props.cardPadCount {Number}

The count of padded cards, necessary for looping.

Ignored if loop is false.

props.cardSize {Number}

The width (or height if vertical is true) in pixels of a card.

props.vertical {Boolean}

Listen to vertical touch moves instead of horizontal ones. Default false.

props.loop {Boolean}

Tail to head, head to tail. Default true.

props.autoplay {Number}

Interval in milliseconds, 0 as disabled. Default 0.

props.defaultCursor {Number}

The cursor value for initial render.

Notice the sign of the number, normally it should be negative or zero(default).

props.onRest(index, modIndex, cursor, carouselState) {Function}

Callback when the carousel is rested at a card.

props.onDragStart/onDragEnd/onDragCancel

Add some listeners if you need.

props.ignoreCrossMove {Number|Boolean}

If deltCrossAxis * ignoreCrossMove > deltMainAxis, carousel would ignore the dragging.

true as 1 and false as 0. Default true.

Concepts

Cursor

A cursor indicates the transition position of the carousel.

When the user swipes right, the number gets bigger. When the user swipes left, the number get smaller.

There are three steps to calculating the cursor's final value: specified, computed, used.

In most cases you just use the used cursor value to render your carousel content.

CarouselState

A carouselState is always passed to your component and renderCard.

It contains:

{
  cursor, // the specified cursor
  active, // is user interacting with the component, no matter dragging or pressing or clicking?
  dragging, // is user dragging the component?
  springing, // has user dragged and released the component, and the component is transitioning to the specified cursor?
  moding // is the cursor moding?
}

Mod

This happens if you enable loop. We keep the cursor in a valid range by "moding" it.

Advanced options

There are some advanced options, but normally you don't need to touch them.

Methods

go(targetCursor)

Transition to a position.

next()

Transition to next card.

prev()

Transition to previous card.

modAs(targetCursor)

Hard jump to a position.

Mouse support

We provide an HOC for very basic mouse support. Internally it simulates touch events with the mouse events.

import touchWithMouseHOC from 'react-touch-carousel/lib/touchWithMouseHOC'

const Container = touchWithMouseHOC(CarouselContainer)

<TouchCarousel
  component={Container}
/>

react-touch-carousel's People

Contributors

bujakasha avatar dependabot[bot] avatar omahlama avatar xiaody avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-touch-carousel's Issues

Speed control

Hello! How we can control scroll speed? Is there such the prop maybe?

NonPassiveTouchTarget

Hi, is this component still needed for iOS Safari? And if so, will it be a part of the lib or should we just copy the one in the examples folder?

cheers,
mg

Follw the usage, I can't use this carousel.

import React from 'react';
import TouchCarousel from 'react-touch-carousel'
class App extends React.Component {

carouselComponent() {
    return (
        <div style={{backgroundColor: "yellow", height:400, width: "90%"}}>

        </div>
    )
}

renderCard(index, modIndex) {
    return (
        <div style= {{color: "red"}}>
            {index}
            <div>
                <div className='carousel-title'>{'title'}</div>
                <div className='carousel-text'>{'text'}</div> 
            </div>
        </div>
    )
}

render() {
    return (
        <TouchCarousel
            component={this.carouselComponent.bind(this)}
            cardCount={3}
            cardSize={375}
            renderCard={this.renderCard.bind(this)}
            loop
            autoplay={3000}
        />
    )
}
}

 export default App

2018-09-03 4 42 28 1

I can't see renderCard's component

Issue in using Rolling Carousel example in another app

Hey there, I'm back again with bad issues.

I've tried out the "rolling" example in a completely separate app. Worked great.
But here I am trying to put it into another, existing app.

The Problem

The cards are not centered, and upon drag, the whole carousel-track starts moving slightly left or right.

Video of the issue:
https://user-images.githubusercontent.com/51885228/188541506-a9e2ecd0-5a53-4d30-b59e-00051cb58d87.mov

The code:

const  cardSize = 100;
const  cardPadCount = 3;
const  carouselWidth = clamp(window.innerWidth, 0, 960);

.
.
.
.

  function CarouselContainer (props) {
    const { cursor, carouselState, ...rest } = props
    // Put current card at center
    const translateX = (cursor - cardPadCount) * cardSize + (carouselWidth - cardSize) / 2

    return (
      <NonPassiveTouchTarget className='carousel-container'>
        <NonPassiveTouchTarget
          className='carousel-track'
          style={{ 
            transform: `translate3d(${translateX}px, 0, 0)`,
          }}
          {...rest}
        />
      </NonPassiveTouchTarget>
    )
}

The styles:

.top-level-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 100vh;
  overflow-x: hidden;
  width: 100vw;
  margin-top: 0;
  margin-left: 0;
  z-index: 99;
}

.carousel-container {
  height: 300px;
  width: 100%;
  margin: 0 auto;
  overflow: hidden;
  touch-action: pan-y;
}

.carousel-track {
  display: flex;
  height: 100%;
}

.carousel-card {
  flex: 0 0 100px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-weight: bold;
  color: white;
  -webkit-tap-highlight-color: transparent;
}

.image-container {
  max-width: 8em;
  max-height: 8em;
  width: 4em;
  height: 4em;
  background-size: cover;  
}

.carousel-card-inner {
  position: relative;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  width: 100px;
  height: 180px;
  color: rgba(0,0,0,.5);
  transition: inherit;
  -moz-box-shadow: 0px 5px 5px 0px rgba(0,0,0,0.3);
  box-shadow: 0px 5px 5px 0px rgba(0,0,0,0.3); */
  border: 5px solid black;
  border-radius: 1.5em;
}

Any thoughts on what's going wrong?

Is there a prop to disable the dragging functionality?

Great work on this awesome framework!

I am using this as a way to navigate between slides, and I've built a full-screen toggle so that you can open a slide in full screen. I want the drag functionality to be disabled in this mode and then renabled when I go back to the carousel view.

Is this something I'd need to code from scratch or is there a disabled={true} prop, or similar? I wasn't sure if this is one of the advanced features alluded to in the docs?

publish version 0.8.4 to npm public registry

I am working a project which is using 0.8.3 version. Currently we received number of errors, which is fixed in this commit. Due to the size of bundle in 0.9 is 3 times bigger than 0.8. We decided to stay in 0.8. Could it possible to publish the 0.8.4 to npm public registry? Thank you.

How to get center Index (cursor) in the beginning?

Hi,
I use onRest to update the center card index, but the problem is that onRest is not called on the initialization of the carousel (I think it should, or there should be a boolean prop for that).

How can I get the center card index / cursor?

white screen

`import React from 'react';
import './Projects.css';
import TouchCarousel from 'react-touch-carousel'
const Projects = () => {

    const myProjects = [
        {
            image: require('../assets/budget.png'),
            title: 'Budget App',
            description: 'A budget app that allows you to track your expenses and income. You can also add new expenses and income to your budget.',
        },
        {
            image: require('../assets/weather.PNG'),
            title: 'Weather App',
            description: 'A weather app that allows you to search for weather conditions in any city. You can also add a new city to your list of cities.',
        },
    
    ]
    function CarouselContainer(){
        // render the carousel structure
        }
        
function renderCard(index, modIndex, cursor){
const item = myProjects[modIndex];
 // render the item 
}

  return (
        
    <TouchCarousel
  component={CarouselContainer}
  cardCount={myProjects.length}
  cardSize={375}
  renderCard={renderCard}
  loop
  autoplay={3000}
></TouchCarousel>
  
  )
}

export default Projects`

what am i missing? my screen just shows blank

Getting error when trying to use data array from state

TypeError: Cannot read property 'image' of undefined

  renderCard = (index, modIndex) => {
    const item = this.state.productImages[modIndex]
    return (
      <div
        key={index}
        className='carousel-card'
        data-index={index}
        data-modIndex={modIndex}
      >
        <div
          className='carousel-card-inner'
        >
          {item.image}
        </div>
      </div>
    )
  }

Enable scroll events?

This is what I have searched for a long time! Awesome!

And any thoughts on add scroll events?

Cannot update a component (`RingComponent`) while rendering a different component (`wrappedCard`)

Hi everyone,

I develop a pwa and i meet a problem with the prev and next function from carousel, i have this issue when i call them.

Screenshot from 2022-05-31 13 17 57

I declare my carousel like that :

const CarouselRef = useRef<any>({
    next: () => null,
    prev: () => null,
  });

i use prev and next like that :

const snapSelectedMember = () => {
    if (!selectedMember) return;
    const index = ordersMembers.findIndex(member => member.id === selectedMember.id) || 0;
    if(index === -1) return;
if (index < currentIndex) {
      for (let i = index; i <= currentIndex; i++) { CarouselRef.current.prev(); }
    } else {
      for (let i = currentIndex; i <= index; i++) { CarouselRef.current.next(); }
    }
    setCurrentIndex(index);
};

and this is my touch carousel :

        ref={CarouselRef}
        component={CarouselContainer}
        cardCount={ordersMembers?.length}
        renderCard={(index: number, modIndex: any, cursor: number, carouselState: any) => RenderCard({ index, modIndex, cursor, carouselState, item: ordersMembers[modIndex], currentIndex, onIndexChange })}
        defaultCursor={currentIndex}
        onDragStart={() => setDisableDraging(true)}
        onDragEnd={() => setDisableDraging(false)}
        onDragCancel={() => setDisableDraging(false)}
        loop={false}
      />

Do you have any idea where come from my issue ?

carousels with slides with images can lose ability to dragEnd

Carousel loses snapping, never fires dragEnd

Chrome v68 – Mac OS 10.13.6

I copied the boring example into my project and added images to each slide. If the image on a slide can be dragged as a semi-transparent copy, the carousel never fires dragEnd and sits lazily wherever it is dragged, no longer snapping into position.

Solutions I'm thinking about are:
a way to watch for or prevent this behavior
a dragTimeout prop on the carousel that could accepts a couple customizing parameters but generally forces dragEnd to be triggered in prescribed circumstances.

touch-carousel-bug-1

image being dragged rather than carousel

touch-carousel-bug

just sits there acting coy, still updating the current slide even

Disable / enable the carousel's movement

Hey there,
Thanks for this amazing repo. Building something super cool with this, but stuck at a place where I want the Carousel to just freeze or "do nothing" upon any touch event or any autoplay etc, if a certain value becomes true.

Possible Solution

Add a boolean prop, e.g. called "play" which disables or enables the carousel's movement. For example:


const [carouselShouldPlay, setCarouselShouldPlay] = useState(true);


...

      <TouchCarousel
          component={Container}
          cardSize={cardSize}
          cardCount={handData.length}
          cardPadCount={cardPadCount}
          renderCard={renderCard}
          play={carouselShouldPlay}
      />

...

If there's already a way to do this, please help me out.

Add TypeScript types

It would be nice if this module could have associated TypeScript-types in DefinitelyTyped. Info on how to create such a type package is documented in their repo.

Here is what I have created so far, if someone wants to build off this:

// Type definitions for react-touch-carousel 0.8
// Project: https://github.com/xiaody/react-touch-carousel
// Definitions by: mikaello <https://github.com/mikaello>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/*import * as React from 'react';

export as namespace TouchCarousel;
export = TouchCarousel;



declare namespace TouchCarousel {*/
//declare module 'react-touch-carousel' {
import * as React from 'react';

export default class TouchCarousel extends React.PureComponent<
  TouchCarouselProps
> {}

export interface TouchCarouselProps {
  /**
       * Your container component of the carousel.
       *
       * react-touch-carousel will pass it's touch listeners, dragging/active state, current position cursor to this component.
       *
       * It is actually called like this:
       * ```jsx
         <Component
           cursor={usedCursor}
           carouselState={carouselState}
           onTouchStart={onTouchStart}
           onTouchMove={onTouchMove}
           onTouchEnd={onTouchEnd}
           onTouchCancel={onTouchCancel}
         >
           {allYourRenderedCards}
         </Component>
        ```
       */
  component?: (props: ComponentProps) => React.ReactElement<any> | null;

  /**
   * The width (or height if `vertical` is `true`) in pixels of a card.
   */
  cardSize?: number;

  /**
   * The count of your cards, not including the padded ones.
   */
  cardCount?: number;

  /**
   * The count of padded cards, necessary for looping.
   *
   * Ignored if `loop` is `false`.
   */
  cardPadCount?: number;

  /**
   * The cursor value for initial render.
   *
   * Notice the sign of the number, normally it should be negative or zero (default).
   */
  defaultCursor?: number;

  /**
   * Tail to head, head to tail. Default `true`.
   */
  loop?: boolean;

  /**
   * Interval in milliseconds, 0 as disabled. Default `0`.
   */
  autoplay?: number;

  /**
   * Listen to vertical touch moves instead of horizontal ones. Default `false`.
   */
  vertical?: boolean;

  /**
   * The card renderer.
   *
   * All rendered cards joined as an array will be passed to props.component as it's `children`.
   */
  renderCard?: (
    index: number,
    modIndex: number,
    cursor: number,
    carouselState: CarouselState,
  ) => React.ReactElement<any> | null;

  precision?: number;

  tension?: number;

  friction?: number;

  moveScale?: number;

  /**
   * Callback when the carousel is rested at a card.
   */
  onRest?: (
    index: number,
    modIndex: number,
    cursor: number,
    carouselState: CarouselState,
  ) => void;

  /**
   * Called when carousel is begun dragged
   */
  onDragStart?: () => void;

  /**
   * Called when carousel movement stopped
   */
  onDragEnd?: () => void;

  /**
   * Called when carousel movement was cancelled
   */
  onDragCancel?: () => void;

  maxOverflow?: number;

  clickTolerance?: number;

  /**
   * If `deltCrossAxis * ignoreCrossMove > deltMainAxis`, carousel would ignore the dragging.
   *
   * `true` as `1` and `false` as `0`. Default `true`.
   */
  ignoreCrossMove?: number | boolean;
}

export interface ComponentProps {
  cursor: number;
  carouselState: CarouselState;
  onTouchStart: (e: TouchEvent) => void;
  onTouchMove: (e: TouchEvent) => void;
  onTouchEnd: (e: TouchEvent) => void;
  onTouchCancel: (e: TouchEvent) => void;
}

export interface CarouselState {
  /**
   * The specified cursor
   */
  cursor: number;

  /**
   * Is the user interacting with the component, no matter dragging or pressing or clicking?
   */
  active: boolean;

  /**
   * Is user dragging the component?
   */
  dragging: boolean;

  /**
   * Has the user dragged and released the component, and the component is transitioning to the specified cursor?
   */
  springing: boolean;

  /**
   * Is the cursor moding?
   */
  moding: boolean;
}

Support Horizontal Scroll

Hey there,
Most carousels support horizontal scrolling e.g. if you scroll with two fingers on a trackpad in the horizontal direction. Can there be a prop to support that?

Example using `next`

Hello! Great library, I love the control it gives you, but I have a question.

I want to add a next button to my ContainerComponent, but I don't know the best way to access that method.

export function Carousel() {
  return h(TouchCarousel, {
    component: ContainerComponent, // <-- I'd like to pass `next` into this component
    cardCount: 3,
    renderCard,
    loop: false,
  });
}

How can I achieve this?

Should mod cursor earlier

Currently update cursor when user touching carousel. Which introduces an issue that if you put like video player inside the carousel, assume we have 7 cards, when you scroll from cursor 0 to cursor -1, touch the -1 video player to start play, it will be modCursor to 6 card with -1 video player playing.

I currently update cursor based on this every time onRest to workaround.

NextJS compability

Hi, I was really looking forward to using this plugin instead of my selfmade piece of garbage that I produced. However, a bug in react-spring v8 is triggering compiler errors in NextJS > 9. The bug was fixed in react-spring v9 (see here).

Is there any realistic chance to get an upgrade to the latest major version of react-spring in the near future?

Advanced Options required

Advanced options and methods required to have a fully customizable carousel
for example Next() fn etc..

getCursor()

what is getCursor() in const cursor = this.carousel.getCursor() line code?
carousel not define in page and after swipe show up this error
Cannot read properties of undefined (reading 'getCursor')

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.