NavehMevorach
NavehMevorach

Reputation: 165

How to add a video to React Responsive Carousel Npm Package?

I am trying to create a Carousel of images and embedded Youtube videos (the first item is a youtube video and the rest are images) I am using the React Responsive Carusel npm package but I can't find a way to create the carousel I want without bugs.

I saw a solution over here but it's only for videos.

Here is my code at the moment:

import React from 'react'
import 'react-responsive-carousel/lib/styles/carousel.min.css' // requires a loader
import { Carousel } from 'react-responsive-carousel'
import ReactPlayer from 'react-player'
const ModalImagesPreview = () => {
    
  return (
    <div>
      <Carousel>
        <div>
          <ReactPlayer
            url='https://www.youtube.com/watch?v=ysz5S6PUM-U'
            volume='1'
            muted
            width='100%'
            playing={true}
          />
        </div>
        <div>
          <img src='https://cdn.dribbble.com/users/2146089/screenshots/12387473/media/bf9ffb522fe68ba57ebdc62bc3f16cc5.png' />
        </div>
        <div>
          <img src='https://cdn.dribbble.com/users/427857/screenshots/12318706/media/f30f662dbf160022412812881b2afb43.jpg' />
        </div>
      </Carousel>
    </div>
  )
}

export default ModalImagesPreview

Thanks for the helpers!

Upvotes: 6

Views: 7133

Answers (2)

Andrey Patseiko
Andrey Patseiko

Reputation: 4495

I applied like this.

const mockData = [
 { type: 'IMAGE', src: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTj_w2LFD5m1UgmMfXJHldMpE8uoGLprqiD6A&usqp=CAU'},
 { type: 'VIDEO', src: 'https://www.youtube.com/embed/NOCw4MoQ3xc' }  
];


const VideoSlide = ({ url, isSelected }: { url: string; isSelected?: boolean }) => {
  const playerRef: MutableRefObject<any> = useRef();

  useEffect(() => {
    playerRef.current.seekTo(0); // reset video to start
  }, [isSelected]);

  return <ReactPlayer width='100%' height='100%' url={url} ref={playerRef} playing={isSelected} />;
};


export const CarouselContainer = () => {

 const customRenderItem = (item: any, props: any) => (
   <div style={...}>
     <div style={{background: 'white'}}>
       <item.type {...item.props} {...props} /> 
    {/* ^-- Item from doc http://react-responsive-carousel.js.org/storybook/?path=/story/02-advanced--youtube-autoplay-with-custom-thumbs  */}
     </div>
   </div>
 );

return (    
  <Carousel
    showThumbs={false}
    axis='horizontal'
    showStatus={false}
    showArrows={false}
    showIndicators={false}
    renderItem={customRenderItem}
  >
    {mockData.map((el, i) => {
      if (el.type === 'IMAGE')
        return <img src={el.src} width='100%' height='100%' alt={`slide-${i}`} />;
      if (el.type === 'VIDEO') return <VideoSlide url={el.src} />;
      return <></>;
    })}
  </Carousel>    
 );
};

Upvotes: 0

DiaMaBo
DiaMaBo

Reputation: 2287

Here is what I found on the react-responsive-carousel website

import 'react-responsive-carousel/lib/styles/carousel.min.css'; // requires a loader
import React from 'react';
import ReactPlayer from 'react-player';
import { Carousel } from 'react-responsive-carousel';
import { PropTypes } from 'prop-types';
import { Grid, makeStyles } from '@material-ui/core';

const DUMMY_VIDEOS = [
  {
   _id: '5fd025a181e2c80897c14ae1',
   videoUrl: 'https://www.youtube.com/embed/AVn-Yjr7kDc'
  }
];

const useStyles = makeStyles(theme => ({
  carousel: {
  margin: theme.spacing(2)
 }
}));

const YoutubeSlide = ({ url, isSelected }) => (
  <ReactPlayer width="100%" height="276px" url={url} playing={isSelected} />
);

const CarouselVideo = ({ data }) => {
  const classes = useStyles();

  const customRenderItem = (item, props) => (
    <item.type {...item.props} {...props} />
  );

  const getVideoThumb = videoId =>`https://img.youtube.com/vi/${videoId}/default.jpg`;

  const getVideoId = url =>url.substr('https://www.youtube.com/watch?v='.length, url.length);

  const customRenderThumb = children =>
    children.map(item => {
      const videoId = getVideoId(item.props.url);
  
      return <img key={videoId} src={getVideoThumb(videoId)} />;
  });

  return (
    <Grid item md={6} xs={12}>
      <Carousel
       autoPlay={false}
       className={classes.carousel}
       emulateTouch={true}
       showArrows={true}
       showThumbs={true}
       showStatus={false}
       infiniteLoop={true}
       renderItem={customRenderItem}
       renderThumbs={customRenderThumb}
     >
      {data.map(v => (
        <YoutubeSlide
          url={v.videoUrl}
          muted
          playing={false}
          key={v._id ? v._id : v.id}
        />
      ))}
     </Carousel>
   </Grid>
  );
 };

 YoutubeSlide.propTypes = {
   url: PropTypes.string,
   isSelected: PropTypes.bool
 };

 CarouselVideo.propTypes = {
   data: PropTypes.array
 };

 CarouselVideo.defaultProps = {
  data: DUMMY_VIDEOS
 };

export default CarouselVideo;

Last step is to call this CarouselVideo where you want to render with your data as props or just call it without passint anythind => this will display the dummy videos I added there. So you can call it like the below:

 // DisplayVideo.js file with default videos as shown below
 const DisplayVideo = () => {
   render( <CarouselVideo />)
 }

 // or with your data
 const DisplayVideo = ({PASS_YOU_DATA_HERE}) => {
   render( <CarouselVideo data={PASS_YOU_DATA_HERE} />)
 }

Result: enter image description here (source: https://www.npmjs.com/package/react-responsive-carousel)

Upvotes: 0

Related Questions