Code Monkey home page Code Monkey logo

better-react-carousel's Introduction

Better React Carousel - Typed

React responsive carousel component w/ grid layout
to easily create a carousel like photo gallery, shopping product card or anything you want

Features

  • RWD
  • Multiple items
  • Multiple rows
  • Infinite loop
  • Support any component as a item to put into grid
  • Show/hide dots
  • Show/hide arrow buttons
  • Autoplay
  • Enable/Disable scroll-snap for each item on mobile device
  • Customized layout (cols & rows) for different breakpoint
  • Customized arrow button
  • Customized dots
  • Support SSR

Install

$ npm install better-react-carousel --save

Usage

Just import the Carousel component from better-react-carousel
and put your item into Carousel.Item

import React from 'react'
import Carousel from 'better-react-carousel'

const Gallery = () => {
  return (
    <Carousel cols={2} rows={1} gap={10} loop>
      <Carousel.Item>
        <img width="100%" src="https://picsum.photos/800/600?random=1" />
      </Carousel.Item>
      <Carousel.Item>
        <img width="100%" src="https://picsum.photos/800/600?random=2" />
      </Carousel.Item>
      <Carousel.Item>
        <img width="100%" src="https://picsum.photos/800/600?random=3" />
      </Carousel.Item>
      <Carousel.Item>
        {/* anything you want to show in the grid */}
      </Carousel.Item>
      {/* ... */}
    </Carousel>
  )
}

Props

Prop Type Default Description
cols Number 1 Column amount rendered per page
rows Number 1 Row amount rendered per page
gap Number | String 10 Margin (grid-gap) for each item/grid in px or %, passed Number will turn to px unit
loop Boolean false Infinite loop or not
scrollSnap Boolean true true for applying scroll-snap to items on mobile
hideArrow Boolean false Show/hide the arrow prev/next buttons
showDots Boolean false Show dots indicate the current page on desktop mode
autoplay Number Autoplay timeout in ms; undefined for autoplay disabled
dotColorActive String '#795548' Valid css color value for active dot
dotColorInactive String '#ccc' Valid css color value for inactive dot
responsiveLayout Array Customized cols & rows on different viewport size
mobileBreakpoint Number 767 The breakpoint(px) to switch to default mobile layout
arrowLeft Element Customized left arrow button
arrowRight Element Customized left arrow button
dot Element Customized dot component with prop isActive
containerStyle Object Style object for carousel container

responsiveLayout

Array of layout settings for each breakbpoint

Setting options

  • breakpoint: Number; Requried; Equals to max-width used in media query, in px unit
  • cols: Number; Column amount in specific breakpoint
  • rows: Number; Row amount in specific breakpoint
  • gap: Number | String; Gap size in specific breakpoint
  • loop: Boolean; Infinite loop in specific breakpoint
  • autoplay: Number; autoplay timeout(ms) in specific breakpoint; undefined for autoplay disabled

e.g.

[
  {
    breakpoint: 800,
    cols: 3,
    rows: 1,
    gap: 10,
    loop: true,
    autoplay: 1000
  }
]

dot

Example

// your custom dot component with prop `isActive`
const MyDot = ({ isActive }) => (
  <span
    style={{
      display: 'inline-block',
      height: isActive ? '8px' : '5px',
      width: isActive ? '8px' : '5px',
      background: '#1890ff'
    }}
  ></span>
)

// set custom dot
<Carousel dot={MyDot} />

Example

Storybook (Don't forget to try on different viewport size)

$ git clone https://github.com/DevPanther/better-react-carousel
$ cd better-react-carousel

$ npm ci
$ npm run storybook

Use case in real world

# clone & install packages
$ npm run dev
# open localhost:8080

LICENSE

MIT

better-react-carousel's People

Contributors

devpanther 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

Watchers

 avatar  avatar

better-react-carousel's Issues

Carousel sliding does not work on different breakpoints

This carousel works well when set with default rows and cols as properties inside the tag:

<Carousel
      cols={5}
      rows={2}
      gap={10}
      loop
      autoplay={undefined}
      responsiveLayout={[
        {
          breakpoint: 1024,
          cols: 4,
          rows: 2,
          gap: 10,
          loop: true,
          autoplay: undefined,
        },
      ]}
      mobileBreakpoint={479}
    >

But when it comes to reducing cols or other properties in smaller breakpoints, the slider automatically slides back to the first slide instantly no matter how many times you click on arrows or dots and having my autoplay disabled:

Check video of this issue: https://drive.google.com/file/d/1ZZhxR1vaSFle793Ur0aX3xLzVOPt5KCa/view?usp=drive_link

Not working

Not working, it working when you use the pages[0] but no change

export const Carousel = <T extends any>({
    items,
    renderItem,
}: CarouselProps<T>) => {
    const {
        scrollRef,
        pages,
        activePageIndex,
        prev,
        next,
        goTo,
        snapPointIndexes,
    } = useSnapCarousel();
    console.log(pages); // is array inside array

    return (
        <div style={styles.root} class="text-white">
            <ul style={styles.scroll} ref={scrollRef}>
                {items.map((item, i) => {
                    return renderItem({
                        item,
                        isSnapPoint: snapPointIndexes.has(i),
                    });
                })}
            </ul>
            <div style={styles.controls} aria-hidden>
                <button
                    type="button"
                    style={{
                        ...styles.nextPrevButton,
                        ...(activePageIndex === 0
                            ? styles.nextPrevButtonDisabled
                            : {}),
                    }}
                    onClick={() => prev()}
                >
                    {String.fromCharCode(8592)}
                </button>
                {pages[0].map((_, i) => (
                    <button
                        type="button"
                        key={i}
                        style={{
                            ...styles.paginationButton,
                            ...(activePageIndex === i
                                ? styles.paginationButtonActive
                                : {}),
                        }}
                        onClick={() => goTo(i)}
                    >
                        {i + 1}
                    </button>
                ))}
                <button
                    type="button"
                    style={{
                        ...styles.nextPrevButton,
                        ...(activePageIndex === pages[0].length - 1
                            ? styles.nextPrevButtonDisabled
                            : {}),
                    }}
                    onClick={() => next()}
                >
                    {String.fromCharCode(8594)}
                </button>
            </div>
            <div style={styles.pageIndicator}>
                {activePageIndex + 1} / {pages[0].length}
            </div>
        </div>
    );
};

Carousel.Item Using in map()

Hello. Thank you for sharing your perfect library.
It really helps to me as a beginner developer.

I would like to use this library with map() function but I have a problem with "key"
How can I use this with map()?

<Carousel.Item key={id}>

because of key error, I could get data from backend but it doesn't showing on the browser.

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

import '../css/bootstrap.min.css';
import '../css/style.css';
import '../css/carousel.css';
import { useEffect, useState } from 'react';

import axios from 'axios';
import Carousel from 'better-react-carousel';
import { baseUrl } from '../components/commonApi/mainApi';

const NewestSmall = () => {
const [book, setbook] = useState([]);
const addr = baseUrl + '/newest';
console.log(addr);

useEffect(() => {
getbook();
}, []);

async function getbook() {
await axios
.get(addr)
.then((response) => {
setbook(response.data);
})
.catch((error) => {
console.log(error);
});
}

return (
<div className='neweast container col-xl-6 col-lg-6'
<div className='carousel container-fluid mt-4'
<Carousel cols={2} rows={1} gap={15} loop
<div
{book.map((book) => {
return (
<Carousel.Item key={book.book_num}
<div id='book-image'
<a href={'/book/' + book.book_num}
<img src={book.book_image} alt={book.book_title} /
</a
</div
<div

#1</p

{book.book_title}</p

{book.category_code}</p
</div
</Carousel.Item
);
})}
;
</div
</Carousel
</div
</div
);
};

export default NewestSmall;

How do I generate items using Array

I am trying to generate multiple items without having to hard code those but it shows an empty carousel for some reason.

Here is the code

const items = useMemo(
    () =>
      Array(12)
        .fill(0)
        .map((_, i) => {
          return (
            <div>
              <Carousel.Item>
                <img
                  width="100%"
                  src="https://picsum.photos/800/600?random=1"
                />
              </Carousel.Item>
            </div>
          );
        }),
    []
  );

  return (
    <div>
      <Carousel
        autoplay={autoplay}
        cols={cols}
        rows={rows}
        gap={gap}
        showDots={showDots}
        hideArrow={hideArrow}
        loop
      >
        {items}
      </Carousel>
    </div>
  );

Option to keep arrows and/or dots visible on mobile

First - thanks for your work on this! ๐Ÿ‘๐Ÿป

The ability to have arrows and/or dots remain visible on mobile resolutions below 1024px would be very helpful. There are situations where a) the content that's able to be scrolled won't have the off-canvas content visible on either side, and b) simply situations where the visual indicator(s) of dots and/or arrows is simply another helpful UI tool for navigating the content in the carousel.

Example of scenario (a) above
1024 px and above:
1024-px-and-above

620 px (content is available to be scrolled but there is not visual indication of that)
620px

Errors with styled components in production

  • Version: 1.1.2
  • Env: vite@latest + react 18.2.0

I know that yesterday you pushed a change to solve this but it didn't work. As far as I am aware, those new options are part of RollUp v3 and I see you're using 1.29.1 so I don't really know if they were supposed to work in the first place.

image

Arrows are not working on mobile

Hii,
Thank you for the amazing package.But i am facing an issue,my navigation arrows are working fine on desktop but on mobile responsive it not working.http://noplan.maastrixdemo.com/step-two.

This is my code.Any help will be appreciated

`
{characters.map((char, index) => (
<Carousel.Item key={index}>



<h2
className={
char.id == selectedCharObj.id
? ""
: "opa_zero"
}
>
P1

<h2
className={
char.id == selectedCharObj2.id
? ""
: "opa_zero"
}
>
P2

                                <a
                                  style={{ border: "1px solid red" }}
                                  className={
                                    Object.keys(selectedCharObj).length ===
                                    0
                                      ? ""
                                      : char.id == selectedCharObj.id ||
                                        char.id == selectedCharObj2.id
                                      ? "active"
                                      : "grayScaled"
                                  }
                                  style={{ cursor: "pointer" }}
                                  onClick={(e) => {
                                    selectCharacter(char);
                                  }}
                                >
                                  <img src={char.image} alt="char" />
                                </a>
                              </div>
                            </Carousel.Item>
                          ))}
                        </Carousel>`

Issue with changing cols property

Issue

I am using the better-react carousel, it's one of the best in the carousels but, I am facing some issues in changing the cols property for the mobile screen. I want to show 5 pictures in small size on a mobile screen but cannot access the depth of the cols property. Am I doing it wrong, or is there another way? I am using Next Js (TypeScript), TailwindCSS.
I've included for you the attached images. The first image shows the gap, I want to remove. The second image shows the property I want to apply for mobile screen by default it is, "grid-template-columns:repeat(5,100%)". I want to change it to, "grid-template-columns:repeat(5,30%)". Please guide me.
Thanks
Screenshot 2023-07-09 232649
Screenshot 2023-07-09 232804

customize arrow, and avoid x-overflow

how can i customize the arrows?
and how can i adjust the total container size to avoid x-overflow

React.App.-.Google.Chrome.2022-12-10.18-49-28.mp4

Doesn't Work In Production

Worked fine in development but the second I ran a production build, I get Cannot read properties of undefined (reading 'withConfig') error and the site breaks. Remove your carousel and the site works again, yours is the only sttyle component I have.

Any advice would be great because this is the best carousel I found during development tests.

Custom Dots Aren't Working

First off I just want to say how amazing this is. Spent all day today trying to get different carousels to work with no luck. Yours is the first that works perfectly.

My issue is with trying to custom style the components. I tried to mimic your dot example // your custom dot component with prop isActive`
const MyDot = ({ isActive }) => (
<span
style={{
display: 'inline-block',
height: isActive ? '8px' : '5px',
width: isActive ? '8px' : '5px',
background: '#1890ff'
}}

)

// set custom dot
` but the dots just disappear. Any advice would be welcome. II tried looking at your JS dot file but it's incredibly complex compared to the readme example.

It's not a huge deal because the default functionality works fine but I'd like to make them slightly larger and include a hover background change.

Thanks again for the amazing component!

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.