Git Product home page Git Product logo

react-material-ui-carousel's Introduction

React Material UI Carousel npm version

Description

A Generic, extendible Carousel UI component for React using Material UI
It switches between given children using a smooth animation.
Provides next and previous buttons. Also provides interactible bullet indicators.

Live Demo

Take a look at this interactible Live Demo

Installation

npm install react-material-ui-carousel --save

Note:

You will need to have Material UI installed, in order to use this library/component

npm install @mui/material
npm install @mui/icons-material
npm install @mui/styles

Other Versions

# Version 2 with MUI 4
npm install react-material-ui-carousel@v2 --save
npm install @material-ui/core
npm install @material-ui/icons


# Version 2 with MUI 5 support
npm install react-material-ui-carousel@v2mui5 --save

Usage Example

import React from 'react';
import Carousel from 'react-material-ui-carousel'
import { Paper, Button } from '@mui/material'

function Example(props)
{
    var items = [
        {
            name: "Random Name #1",
            description: "Probably the most random thing you have ever seen!"
        },
        {
            name: "Random Name #2",
            description: "Hello World!"
        }
    ]

    return (
        <Carousel>
            {
                items.map( (item, i) => <Item key={i} item={item} /> )
            }
        </Carousel>
    )
}

function Item(props)
{
    return (
        <Paper>
            <h2>{props.item.name}</h2>
            <p>{props.item.description}</p>

            <Button className="CheckButton">
                Check it out!
            </Button>
        </Paper>
    )
}

Next & Prev Usage

    <Carousel
        next={ (next, active) => console.log(`we left ${active}, and are now at ${next}`); }
        prev={ (prev, active) => console.log(`we left ${active}, and are now at ${prev}`); }
    >
        {...}
    </Carousel>

    // OR

    <Carousel
        next={ () => {/* Do stuff */} }
        prev={ () => {/* Do other stuff */} }
    >
        {...}
    </Carousel>

    // And so on...

Note: onChange works in a similar fashion. See Props below.

Customizing Navigation

Navigation Buttons - Customizing the default solution

These are the props that are used to directly customize the Carousel's default buttons:

  • NextIcon
  • PrevIcon
  • navButtonsProps
  • navButtonsWrapperProps
  • fullHeightHover

Example #1

Say we don't like the default icons used for the next and prev buttons and want to change them to be an MUI Icon or an image of our own.

import RandomIcon from '@@mui/icons-material/Random'; // Note: this doesn't exist

<Carousel
    NextIcon={<RandomIcon/>}
    PrevIcon={<RandomIcon/>}
    // OR
    NextIcon={<img src="http://random.com/next"/>}
    PrevIcon={<img src="http://random.com/prev"/>}
>
    {...}
</Carousel>

The NextIcon and PrevIcon is of type ReactNode, meaning it can be any JSX element or a string. Note: Extra styling may be needed when using those props.

Example #2

Let's now say we don't like the default graphite background of the buttons, nor do we like the fact that it is round.
We also want to place them under the main Carousel, and finally remove the arrows and have "next" and "prev" accordingly to each button.

A very important note here, is that any styles specified by the user DO NOT OVERRIDE THE EXISTING STYLES. They work in tandem with them. That means, that if you want to change, or get rid of a CSS attribute you will have to override it or unset it. The Default styles are given at the end of this section, and are part of the code.

<Carousel
    fullHeightHover={false}     // We want the nav buttons wrapper to only be as big as the button element is
    navButtonsProps={{          // Change the colors and radius of the actual buttons. THIS STYLES BOTH BUTTONS
        style: {
            backgroundColor: 'cornflowerblue',
            borderRadius: 0
        }
    }} 
    navButtonsWrapperProps={{   // Move the buttons to the bottom. Unsetting top here to override default style.
        style: {
            bottom: '0',
            top: 'unset'
        }
    }} 
    NextIcon='next'             // Change the "inside" of the next button to "next"
    PrevIcon='prev'             // Change the "inside of the prev button to "prev"
>
    {...}
</Carousel>

Of course, extra styling to the button wrappers, or indicators might be needed to achieve exactly what we may be looking for. Note: You can also use className to change the styles externally.

Customizing the navigation buttons directly

Do directly customize/change the navigation buttons NavButton prop, that allows the user to take complete control of the components rendered as the navigation buttons. It should be used like this:

Example

import {Button} from '@mui/material';

<Carousel
    NavButton={({onClick, className, style, next, prev}) => {
        // Other logic

        return (
            <Button onClick={onClick} className={className} style={style}>
                {next && "Next"}
                {prev && "Previous"}
            </Button>
        )
    }}
>
    {...}
</Carousel>
Parameters Explanation
  • onClick: The function that handles actual navigation. If you do not add this to your component, the buttons will not work.
  • className: The className given by the carousel component. This is used to handle Visible/Invisible, hover, and user specified styles (e.g. from navButtonProps). Apply it to the outmost element.
  • style: The style given by the carousel component. Used to give any user specified styles (e.g. from navButtonProps).
  • next: Boolean value that specifies whether this is the next button.
  • prev: Boolean value that specifies whether this is the prev button.

The prop value must be a function that returns a component. All parameters are optional as far as styling goes (not functionality), but it is advised you use them as shown above.
As implied, any classNames or styles specified in the navButtonsProps will only be used iff you apply the given className and style parameters.

Customizing the Indicators

There are 4 props that handle indicator customization

  • IndicatorIcon
  • activeIndicatorIconButtonProps
  • indicatorIconButtonProps
  • indicatorContainerProps

Example

Let's say we would like to change the indicator icon from a circle to a something else, for example a little house

import Home from '@mui/icons-material/Home';

<Carousel
    IndicatorIcon={<Home/>}
    // OR
    IndicatorIcon={<img src="http://random.com/home"/>}
>
    {...}
</Carousel>

The IndicatorIcon works the same way as the NextIcon and PrevIcon prop.

Example #2

Let's say we would like to have an array to icons like numbers, to order the elements of my carousel numerically. Let's do this!

const anArrayOfNumbers = [<img src="http://random.com/one"/>, 
                          <img src="http://random.com/two"/>, 
                          <img src="http://random.com/three"/>
                         ];

<Carousel
    IndicatorIcon={anArrayOfNumbers}
>
    {...}
</Carousel>

Example #3

Now we want to do more complex customizations. Specifically:

  1. More distance between the indicator icons
  2. Change the background color of the active indicator to red
  3. Change the color of all indicators to blue
  4. Move the indicators to the right side of the carousel
  5. Move the indicators to be further away down from the carousel

We are going to use all props to style the indicators

import Home from '@mui/icons-material/Home';

<Carousel
    IndicatorIcon={<Home/>} // Previous Example
    indicatorIconButtonProps={{
        style: {
            padding: '10px',    // 1
            color: 'blue'       // 3
        }
    }}
    activeIndicatorIconButtonProps={{
        style: {
            backgroundColor: 'red' // 2
        }
    }}
    indicatorContainerProps={{
        style: {
            marginTop: '50px', // 5
            textAlign: 'right' // 4
        }

    }}
>
    {...}
</Carousel>

As before, you can use className to style the elements externally.

Default Styles

Giving the default styles in pseudo-code.

Navigation Buttons

{
    buttonWrapper: {
        position: "absolute",
        height: "100px",
        backgroundColor: "transparent",
        top: "calc(50% - 70px)",
        '&:hover': {
            '& $button': {
                backgroundColor: "black",
                filter: "brightness(120%)",
                opacity: "0.4"
            }
        }
    },
    fullHeightHoverWrapper: {
        height: "100%",
        top: "0"
    },
    buttonVisible:{
        opacity: "1"
    },
    buttonHidden:{
        opacity: "0",
    },
    button: {
        margin: "0 10px",
        position: "relative",
        backgroundColor: "#494949",
        top: "calc(50% - 20px) !important",
        color: "white",
        fontSize: "30px",
        transition: "200ms",
        cursor: "pointer",
        '&:hover': {
            opacity: "0.6 !important"
        },
    },
    // Applies to the "next" button wrapper
    next: {
        right: 0
    },
    // Applies to the "prev" button wrapper
    prev: {
        left: 0
    }
}

Indicators

{
    indicators: {
        width: "100%",
        marginTop: "10px",
        textAlign: "center"
    },
    indicator: {
        cursor: "pointer",
        transition: "200ms",
        padding: 0,
        color: "#afafaf",
        '&:hover': {
            color: "#1f1f1f"
        },
        '&:active': {
            color: "#1f1f1f"
        }
    },
    indicatorIcon: {
        fontSize: "15px",
    },
    // Applies to the active indicator
    active: {           
        color: "#494949"
    }
}

Props

Prop name Type Default Description
sx SxProps<Theme> {} Defines sx props, that will be inserted into the Carousel 's root element
className string "" Defines custom class name(s), that will be added to Carousel element
height number | string undefined Defines the carousel's height in px. If this is not set, the carousel's height will be the height of its children. If it is not set, the carousel's height will be the same as the current active child.
index number 0 Defines which child (assuming there are more than 1 children) will be displayed. Next and Previous Buttons as well as Indicators will work normally after the first render. When this prop is updated the carousel will display the chosen child. Use this prop to programmatically set the active child. If (index > children.length) then if (strictIndexing) index = last element. index
strictIndexing boolean true Defines whether index can be bigger than children length
autoPlay boolean true Defines if the component will auto scroll between children
stopAutoPlayOnHover boolean true Defines if auto scrolling will continue while mousing over carousel
interval number 4000 Defines the interval in ms between active child changes (autoPlay)
animation "fade" | "slide" "fade" Defines the animation style of the Carousel
duration number 500 Defines the duration of the animations.
swipe boolean true Defines if swiping left and right (in touch devices) triggers next and prev behaviour
indicators boolean true Defines the existence of bullet indicators
navButtonsAlwaysVisible boolean false Defines if the next/previous buttons will always be visible or not
navButtonsAlwaysInvisible boolean false Defines if the next/previous buttons will always be invisible or not
cycleNavigation boolean true Defines if the next button will be visible on the last slide, and the previous button on the first slide. Auto-play also stops on the last slide. Indicators continue to work normally.
fullHeightHover boolean true Defines if the the next/previous button wrappers will cover the full height of the Item element and show buttons on full height hover
navButtonsWrapperProps {className: string, style: React.CSSProperties} & React.AriaAttributes undefined Used to customize the div surrounding the nav IconButtons. Use this to position the buttons onto, below, outside, e.t.c. the carousel. Tip: Check the default styles below.
navButtonsProps {className: string, style: React.CSSProperties} & React.AriaAttributes undefined Used to customize the actual nav IconButtons
NextIcon ReactNode <NavigateNextIcon/> Defines the element inside the nav "next" IconButton. Refer to MaterialUI Button Documentation for more examples. It is advised to use Material UI Icons, but you could use any element (<img/>, <div/>, ...) you like.
PrevIcon ReactNode <NavigateNextIcon/> Defines the element inside the nav "prev" IconButton. Refer to MaterialUI Button Documentation for more examples. It is advised to use Material UI Icons, but you could use any element (<img/>, <div/>, ...) you like.
NavButton ({onClick, className, style, prev, next}: {onClick: Function, className: string, style: React.CSSProperties, next: boolean, prev: boolean}) => ReactNode undefined Gives full control of the nav buttons. Should return a button that uses the given onClick. Works in tandem with all other customization options (navButtonsProps, navButtonsWrapperProps, navButtonsAlwaysVisible, navButtonsAlwaysInvisible, fullHeightHover, ...). Refer to the example section for more information.
indicatorIconButtonProps {className: string, style: React.CSSProperties} & React.AriaAttributes undefined Used to customize all indicator IconButtons. Additive to activeIndicatorIconButtonProps. Any aria-label property used will be rendered with the indicator index next to it. e.g. {'aria-label': 'indicator'} --> 'indicator 1'
activeIndicatorIconButtonProps {className: string, style: React.CSSProperties} & React.AriaAttributes undefined Used to customize the active indicator IconButton. Additive to indicatorIconButtonProps.
indicatorContainerProps {className: string, style: React.CSSProperties} & React.AriaAttributes undefined Used to customize the indicators container/wrapper.
IndicatorIcon ReactNode <FiberManualRecordIcon size='small' className={classes.indicatorIcon}/> Defines the element inside the indicator IconButtons Refer to MaterialUI Button Documentation for more examples. It is advised to use Material UI Icons, but you could use any element (<img/>, <div/>, ...) you like.
onChange (now?: number, previous?: number) => any () => {} Function that is called after internal setActive() method. The setActive() method is called when the next and previous buttons are pressed, when an indicator is pressed, or when the index prop changes. First argument is the child we are going to display, while the second argument is the child that was previously displayed. Will be called in conjunction with and after next and prev props if defined. It will not get called in first render, except if changeOnFirstRender is defined
changeOnFirstRender boolean false Defines if onChange prop will be called when the carousel renders for the first time. In componentDidMount
next (now?: number, previous?: number) => any () => {} Function that is called after internal next() method. First argument is the child we are going to display, while the second argument is the child that was previously displayed
prev (now?: number, previous?: number) => any () => {} Function that is called after internal prev() method. First argument is the child we are going to display, while the second argument is the child that was previously displayed

License

The MIT License.

Author

Learus

react-material-ui-carousel's People

Contributors

8bitaron avatar cansin avatar dependabot[bot] avatar diaver avatar evotech3 avatar hajineats avatar hamidreza-nateghi avatar learus avatar matyas-igor avatar mayankmandloi avatar michaelshum321 avatar nicolasmartinez0510 avatar salahaddin avatar simo97 avatar sunhoww 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-material-ui-carousel's Issues

Module not found in react typescript project

I found an error when import this module
Module not found: Can't resolve 'react-material-ui-carousel' in '../src/component'

import React from 'react';
import Carousel from 'react-material-ui-carousel';
import { Paper, Button } from '@material-ui/core';

Thank you for incoming response

How to get onChange event for slides in autoPlay or on indicator press

Love this plugin!

wondering how to do trigger a change slide event on press of one of the indicator buttons. I know there's a next prev trigger on the arrow buttons on the side, which fires a next and prev event on the carousel but is there any way to get one on the indicator dots? Either A. IF you are using your default carousel dots or B. If you came up with your own custom dots

Flash of background between transitions

Firstly, great job. It's been hard to find something suits my needs, I'm really liking what I see.

My only issue is that on each slide transition, the card being removed is hidden abruptly, and the background is shown as the next card slides or fades into view.

Would it be possible to animate the current card away?

Again, great job.

Timeout not implemented

Hello there,
in the documentation there is some talk about the "timeout" prop but upon checking your code the timeout prop for fade and slide is hardcoded to 500 and 200 ms respectively which is a bit too aggressive.
Best regards

If last Item of Children Array Deleted, no Child is Displayed

I'm using the carousel for a dynamic array of children that can be grown and individual children deleted. The carousel doesn't work as I would expect if I delete the last child of the array. I would prefer if it either circled back to the first child, or to the prev child. Right now it doesn't select anything and you need to manually select from the button bar.

visible the previous image before hide the current image

I'm using the slider and set theautoPlay to true and the animation to slide and when sliding the images it makes the vertical scroll for a second and disappear but that unwanted behavior, so I figure it out and I found that the carousel needs for backface-visibility to set for hidden, so for that I'll make a pull request to solve this issue , you can assign this issue to me

return statement needed inside the map function in order to show the paper

I've used this a few hours ago with nextjs and I couldn't get the paper without putting return like this. So I would like to inform this for your references. Thank you. Also would like to say that this library is super cool.

<Carousel animation="slide">
        {items.map((item, key) => {
          return (
            <div key={key}>
              <Item item={item} />
            </div>
          );
        })}
      </Carousel>

Slide element by element instead of row

Is it possible to render a row of 4 elements and when the carousel slides the first element goes to the end of the list and the element that is in the 5th position occupies the 4th?

Yarn install issue

Hi, thank you for this awesome library !

I'm trying to install your package with yarn.
Is it even possible ? It might be a beginner misunderstanding from me.

It works with npm, but with yarn it seems to hit a network issue :

[2/4] Fetching packages...
info There appears to be trouble with your network connection. Retrying...

I tried to remove the package with yarn and everything worked again.

What I did :

yarn add react-material-ui-carousel

network issue

npm install react-material-ui-carousel

then

yarn

network issue

I also tried this :

    yarn config delete proxy
    npm config rm proxy
    npm config rm https-proxy

I shouldn't mess with two packages managers, NPM seems to remove dependencies from my project's
packages to do his sauce, and I prefer yarn as I'm more experienced with it.
Any clue or tips about this ?

Thank you ! :)

TS Typings Are Incorrect

In the current version, the index.d.ts is incorrectly defined.

    indicatorProps: {className: string, style: React.CSSProperties},
    activeIndicatorProps: {className: string, style: React.CSSProperties},

Those should be nullable it seems. With Typescript, it is complaining if you don't define those.

Is this intentional?

Update Example: "key" prop' warning

for all that have the same error with
Unable to eliminate 'Each child in a list should have a unique "key" prop' warning.

will fix it:

<Carousel>
  {
          items.map(item => <React.Fragment key={item.id}><Item item={item} /></React.Fragment>)
        }
</Carousel>

Autoplay Causing The Full Carousel To Delay Load

Hi. First great library its working near perfect for me. Here is the carousel I built

<Carousel
    animation="slide"
    autoPlay={true}
    interval={9000}
>
     {items.map(test => (
         <Banner item={test} />
      ))}        
</Carousel>

My data is loading fine in the banner my problem is I want the interval between pages once the carousel is already loaded to be different than the time it takes for the carousel to load on to the page.

So When a user opens my page it takes a full 9 seconds for the carousel to load which is a problem since I do want there to be a 9 second interval from the slide effect. Is there anyway I can get the carousel to load instantly but still keep my 9 second interval time?

Note: Even if I get rid of the interval the carousel still does not load immediately it only loads when I press the button I would like so it no button is needed to press.

Thank you

Carousel keeps focus

When i put the carousel at the top of the page then scroll all the way down it scrolls back to the top of the page after each image change the carousel makes.

StartIndex

Assuming there is an array of data to display, I really want to specify the first data to come up on the carousel. For instance, if I click on a particular image, I want it to be the first Item to come up before other images, simply put it should be the first index to show. React-bootstrap carousel has this functionality. I really like the how next and prev icon on hover that this exhibits but had to suspend it for now due to the index set back. Thanks and looking forward to having a reply very soon Sir.

CSS equivalent

I am trying to get the sample up an running and it turns out the scss file with the demo doesn't seem to parse right. Rather than go down the rabbit hole of figuring out what the problem is, would it be possible to get the equivalent CSS file? I just want to get the demo up and running. The scss file goes with this sample . This is the specific file.

License

This is cool.

Any chance we could get a license added to the repo? I understand it is intended to be MIT.

Callbacks for next/previous transition

I wanted to do some conditional rendering on the page outside of this component, based on the current item active in the carousel - i.e, update their state based on carousel next/previous item transitions. Couldn't see anything like this in the code - is this something you'd consider merging if I submitted a PR for it? Sounds fairly trivial, but might need your input on what data you'd like passed to the callback function (...assuming you want this implemented at all...!)

Don't work when clone

I clone the project and tried to reproduce.. But I have the error:

Could not find a required file.
Name: index.html
Searched in: D:\CARPETA_DE_JOSE\PROYECTOS_JAVASCRIPT\react-material-ui-carousel\public

Hide left/right nav buttons

Is there a way to hide the left/right nav buttons like you can hide the indicators?

I did get around this by accessing it through the classes on Carousel, just thought it would be a nice add on.

The reason I needed this is similar to your first example where the left/right nav buttons are covering up a button within the carousel.

carousel length not updating

I am sending different photos [] arrays to my carousel component which vary in data and length but only the initial length sets the carousel indicators after that it doesn't vary depending on the new length of the array. Please help!!

navButtonsAlways visible is not working for me

is this right? <Carousel
className={classes.slide}
animation={"slide"}
navButtonsAlwaysVisible={true} > //is this line right? the navButtonsAlwaysVisible is not working on my project. Apart from this this carousel is the best material ui carousel i have seen so far. nice one bro
{data.map(event => )}

Originally posted by @gakin95 in #57 (comment)

TypeScript example doesn't seem to work

I basically converted the Example app to TypeScript:

import React, { FC } from 'react';
import { navigate } from 'gatsby';
import Carousel from "react-material-ui-carousel"
import autoBind from "auto-bind"
import { CarouselItem } from './CarouselItem';
import '../../assets/scss/carouselbanner.scss';

import {
    Card,
    CardContent,
    CardMedia,
    Typography,
    Grid,
    Button,
} from '@material-ui/core';
import { number } from 'prop-types';

type BannerProps = {
    onClick: (event) => void;
    banneritem: CarouselItem;
    length?: number;
    contentPosition: 'left' | 'right' | 'middle';
};
const Banner:FC<BannerProps> = ({onClick, banneritem, length = 3, contentPosition}) => {
    const totalItems = length;
    const mediaLength = totalItems - 1;

    let items = [];
    const content = (
        <Grid item xs={12 / totalItems} key="content">
            <CardContent className="Content">
                <Typography className="Title">
                    {banneritem.Name}
                </Typography>

                <Typography className="Caption">
                    {banneritem.Caption}
                </Typography>

                <Button onClick={(e) => onClick(e)} variant="outlined" className="ViewButton">
                    Start Now
                </Button>
            </CardContent>
        </Grid>
    )


    for (let i = 0; i < mediaLength; i++) {
        const sideitem = banneritem.Items[i];

        const media = (
            <Grid item xs={12 / totalItems} key={sideitem.Name}>
                <CardMedia
                    className="Media"
                    image={sideitem.Image}
                    title={sideitem.Name}
                >
                    <Typography className="MediaCaption">
                        {sideitem.Name}
                    </Typography>
                </CardMedia>

            </Grid>
        )

        items.push(media);
    }

    if (contentPosition === "left") {
        items.unshift(content);
    } else if (contentPosition === "right") {
        items.push(content);
    } else if (contentPosition === "middle") {
        items.splice(items.length / 2, 0, content);
    }

    return (
        <Card raised className="Banner">
            <Grid container spacing={0} className="BannerGrid">
                {/* {items} */}
            </Grid>
        </Card>
    )
}
type CarouselBannerProps = {
    items: CarouselItem[]
};
type CarouselBannerState = {
    autoPlay: boolean;
    timer: number;
    animation: 'fade' | 'slide' | undefined;
    indicators: boolean;
    timeout: number;
    navButtonsAlwaysVisible: boolean;
    navButtonsAlwaysInvisible: boolean;
}

class CarouselBanner extends React.Component<CarouselBannerProps, CarouselBannerState> {
    constructor(props: CarouselBannerProps) {
        super(props);

        this.state = {
            autoPlay: true,
            timer: 500,
            animation: 'fade',
            indicators: true,
            timeout: 500,
            navButtonsAlwaysVisible: false,
            navButtonsAlwaysInvisible: false
        }

        autoBind(this);
    }

    toggleAutoPlay() {
        this.setState({
            autoPlay: !this.state.autoPlay
        })
    }

    toggleIndicators() {
        this.setState({
            indicators: !this.state.indicators
        })
    }

    toggleNavButtonsAlwaysVisible()
    {
        this.setState({
            navButtonsAlwaysVisible: !this.state.navButtonsAlwaysVisible
        })
    }

    toggleNavButtonsAlwaysInvisible()
    {
        this.setState({
            navButtonsAlwaysInvisible: !this.state.navButtonsAlwaysInvisible
        })
    }

    changeAnimation(event) {
        this.setState({
            animation: event.target.value
        })
    }

    changeTimeout(event, value: number) {
        this.setState({
            timeout: value
        })
    }

    onClickStart(event) {
        navigate('/public/gettingstarted');
    }

    render() {
        return (
            <div style={{marginTop: "50px", color: "#494949"}}>
                <Carousel
                    className="Example"
                    autoPlay={this.state.autoPlay}
                    animation={this.state.animation}
                    indicators={this.state.indicators}
                    timeout={this.state.timeout}
                    navButtonsAlwaysVisible={this.state.navButtonsAlwaysVisible}
                    navButtonsAlwaysInvisible={this.state.navButtonsAlwaysInvisible}
                >
                    {
                        this.props.items && this.props.items.map((item, index) => {
                            return <Banner onClick={this.onClickStart} banneritem={item} key={index} contentPosition={item.contentPosition}/>
                        })
                    }
                </Carousel>
            </div>
        )
    }
}
 
export default CarouselBanner;

But now it I don't see anything. I can go back to normal JSX but I would rather not. Can you see how TypeScript would cause it to fail. NOTE: There are no errors on the console. Just no display.

Conflicting Styles with Material UI - Use Peer Dependency Instead?

Problem

Using <Carousel> and Material UI at the same time causes styles to clash, breaking Material UI

Sample

Without <Carousel> rendered in app

image

With <Carousel> rendered in app.

image

How to reproduce

npx create-react-app my-app
cd my-app
npm start

Add the following to package.json

   "@material-ui/core": "4.10.2",
    "react-material-ui-carousel": "1.6.0",

Modify App.js

import React from 'react';
import './App.css';
import Button from "@material-ui/core/Button";
import Carousel from "react-material-ui-carousel";
import Box from "@material-ui/core/Box";

function App() {
  return (
    <div >
      <Box p={5} >
        <Button variant="contained" color="primary" type="submit">
          Submit
        </Button>
        <Carousel>
          <div key={1}>item 1</div>
          <div key={2}>item 2</div>
        </Carousel>

      </Box>
    </div>
  );
}

export default App;

yarn install & yarn start Start the app and observe the clashing styles on .MuiButtonBase-root and etc...

Possible Fix

Move Material ui and icons to peer dependencies. See mui/material-ui#15610 (comment)

i.e.

"devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "gh-pages": "^2.2.0",
    "@material-ui/core": "^4.10.2",
    "@material-ui/icons": "^4.9.1"
  },
  "peerDependencies": {
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "@material-ui/core": "^4.10.2",
    "@material-ui/icons": "^4.9.1"
  }

Warning: Can't perform a React state update on an unmounted component.

Every once and a while. I am assuming when I unmount the carousel during a repaint. I get the following warning message:

index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
    in Carousel (created by WithStyles(Carousel))
    in WithStyles(Carousel) (at CarouselBanner.jsx:197)
    in div (at CarouselBanner.jsx:196)
    in CarouselBanner (created by Context.Consumer)
    in withRouter(CarouselBanner) (at Dashboard.js:6)
    in Dashboard (created by Context.Consumer)
    in Route (at Public.js:27)

Maybe there needs to be some cleanup when the component unmounts?

respect slide direction on swipe left/right

Hello,

thanks for this nice library. I think visually it would make sense if the slide direction is reverted if "prev" is triggered. Currently the slide is always to left, but if you swipe backwards I think to right might be little bit more consistent.

Internal error?

Taken from the examples I have a react component that implements a CarouselBanner. This seems to work fine as long I am running locally but when I go to bundle it up for production via 'yarn build' (which triggers gatsby build) my gatsby build throws the error

failed Building static HTML for pages - 16.475s

 ERROR #95313 

Building static HTML failed for path "/dashboard/"

See our docs page for more info on this error: https://gatsby.dev/debug-html


  332 |                 indicators ? _react2.default.createElement(Indicators, {
  333 |                     classes: classes,
> 334 |                     length: this.props.children.length,        
      | ^
  335 |                     active: this.state.active,
  336 |                     press: this.pressIndicator,
  337 |                     indicatorProps: this.props.indicatorProps, 


  WebpackError: TypeError: Cannot read property 'length' of undefined  

  - Carousel.js:334 
    node_modules/react-material-ui-carousel/dist/components/Carousel.js    :334:1

Notice that the error is coming from node_modules which this component. Right?

Module parse failed: Unexpected token (3:16)

I'm having this problem trying to run my project including this plugin:

 ERROR in ./node_modules/react-material-ui-carousel/dist/style/Carousel.scss 3:16
    Module parse failed: Unexpected token (3:16)
    You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
    | $grey: rgb(175, 175, 175);
    | $graphite: rgb(73, 73, 73);
    > $small-font-size: 15px;
    | $big-header-font-size: 30px;
    | 
     @ ./node_modules/react-material-ui-carousel/dist/components/Carousel.js 31:0-33
     @ ./node_modules/react-material-ui-carousel/dist/index.js
     @ ./src/components/Elements/HomePage/modules/views/HomePageSection.js
     @ ./src/components/Pages/HomePage.js
     @ ./src/index.js
     @ multi babel-polyfill ./src/index.js
    Child html-webpack-plugin for "index.html":
         1 asset
        Entrypoint undefined = index.html
        [0] ./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html 1.19 KiB {0} [built]
        [2] (webpack)/buildin/global.js 472 bytes {0} [built]
        [3] (webpack)/buildin/module.js 497 bytes {0} [built]
            + 1 hidden module
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] build: `webpack --mode production && npm run copy:assets`
npm ERR! Exit status 2

What's the problem here?

rtl support

The navButtons icons arent correct (180deg rotated) in RTL mode, how to solve it? should I add a css style for that?

Screenshot from 2020-09-01 19-26-28

Example

Hi, This is a great work, well done.

Please how do you make the eBay™ style example, I need to make something like that, But the documentation isn't clear on how to.
Could you please give some hints.

Regards

Being able to style the "active" indicator dot

Thanks again for this learus!

I was dealing with the problem of not being able to style the "active" dot, because it only has a classes.active class name, which gets changed by mui on build and ends up being unpredictable. it would be great to give devs access to a static, pure css class name on the active indicator dot, for purposes of styling the active indicator (since consumers don't have access to the indicators as elements in the component, and since mui changes the "active" class name when it gets compiled to jssXXX".

react-scripts should go in dev dependencies

Not sure but I think react-scripts should go to devDependencies, shouldn't it? Otherwise npm installs a whole bunch of packages on your consumers machines they probably don't need (~100MB).

Customize navButtons

Thanks for the carousel - is there a way to customize the nav buttons and bottom buttons? I know it takes a className prop but I cant get this to style the buttons.

npm run build auto-bind error

yo @Learus , Im trying to build my app but i got this error. Im using latest version of react-material-ui-carousel(1.6.0), auto-bind(2.1.1). Any idea?

Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

./node_modules/react-material-ui-carousel/node_modules/auto-bind/index.js:4

Read more here: http://bit.ly/2tRViJ9

TypeScript Required Prop indicatorContainerProps Should be Optional

hi, I'm using this project with typescript, and I think the Typescript interface CarouselProps has a required prop that should be optional.

The member in question is indicatorContainerProps - none of the examples provided have this member set, and the code works when making the field optional.

Here's the CodeSandbox, using c-r-a w/ typescript. https://codesandbox.io/s/kind-matsumoto-tt16n

you can see that there's a typescript compiler error when you hover over the <Carousel> tag on line 52 in App.tsx but the page is still functional and the Carousel works as-expected.

Let me know if this is as intended and I can throw in a fix to the typing (just making indicatorContainerProps optional) or whatever fits you :)

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.