4

Here is the carousel I am using: react-slick

I want to be able to scroll through each slide using the mouse scroll up or down event.

Scroll up to increment, scroll down to decrement.

Found an example online of exactly what I need - just unsure of how to convert this into a react solution.

Example: https://codepen.io/Grawl/pen/mMLQQb

What would be the best way to achieve this in a "react" component based approach?

Here is my react component:

import React from 'react';
import PropTypes from 'prop-types';
import styles from './styles.css';
import ReactSVG from 'react-svg';
import Slider from 'react-slick';


import MobileSVG from '../../../assets/svg/icons/Mobile_Icon_Option2.svg';
import TabletSVG from '../../../assets/svg/icons/Tablet_Icon_Option2.svg';
import DesktopSVG from '../../../assets/svg/icons/Desktop_Icon_Option2.svg';

const deviceIcons = {'mobile': MobileSVG, 'tablet': TabletSVG, 'desktop': DesktopSVG};

import BackToTopButton from '../BackToTopButton';

export default class ProductComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };

    }

    render() {
        const {productData} = this.props

        //Slider settings
        const settings = {
            dots: true,
            infinite: false,
            speed: 500,
            fade: true,
            arrows: false,
            centerMode: true,
            slidesToShow: 1,
            slidesToScroll: 1
        }

        //Slider items
        const sliderItems = productData.map((obj, i) => {
            return (
                <div className="product-component row" key={i}>
                    <div className="product-component-image-wrap col-xs-12 col-sm-8">
                        <span className="product-heading">{obj.category}</span>
                        <div className="product-detail-wrap">
                            <img className="product-component-image" src={`${process.env.DB_URL}${obj.image}`} />
                            <ul className="list-device-support">
                                {obj.categoryDeviceSupport.map((obj, i) => {
                                    return (<li key={i}>
                                        <span className="svg-icon">
                                            <ReactSVG path={deviceIcons[obj.value]} />
                                        </span>
                                        <span className="product-label">{obj.label}</span>
                                    </li>)
                                })}
                            </ul>
                        </div>
                    </div>
                    <div className="product-component-info col-xs-12 col-sm-3"> 
                        <span className="align-bottom">{obj.title}</span>
                        <p className="align-bottom">{obj.categoryBrief}</p>
                    </div>
                </div>
            )
        });
        return (
            <div className="product-component-wrap col-xs-12">
                <Slider {...settings}>
                    {sliderItems}
                </Slider>
                <BackToTopButton scrollStepInPx="50" delayInMs="7" />
            </div>
        )
    }
}

ProductComponent.propTypes = {
    productData: PropTypes.array
};

ProductComponent.defaultProps = {
    productData: []
};
Filth
  • 3,116
  • 14
  • 51
  • 79

5 Answers5

8

You'd wanna do something like this:

constructor(props){
    super(props);
    this.slide = this.slide.bind(this);
}
slide(y){
    y > 0 ? (
       this.slider.slickNext()
    ) : (
       this.slider.slickPrev()
    )
}
componentWillMount(){
    window.addEventListener('wheel', (e) => {
        this.slide(e.wheelDelta);
    })
}
render(){...

and add a ref to your slider:

<Slider ref={slider => this.slider = slider }>

So when the y value of the wheel event is greater than 0 i.e. scroll up then show next slide, when scrolling down show previous.

Robbie Milejczak
  • 5,664
  • 3
  • 32
  • 65
  • Firstly, thank you kindly for your reply. I'm getting a funny error when trying to scroll: Failed to execute 'scroll' on 'Window': parameter 1 ('options') is not an object. Is it potentially because of using eventListener "wheel"? – Filth Dec 04 '17 at 21:32
  • its probably a context issue, change the name of the `scroll` function to `slide` or something and change the event listener callback to a fat arrow – Robbie Milejczak Dec 05 '17 at 13:18
  • I'm not sure what you mean by change the event listener callback to a fat arrow? – Filth Dec 05 '17 at 14:20
  • Sorry, a fat arrow is an es6 syntax thing. Its just a different way to define a function instead of `function(e){}` you say `(e) => {}`. I added it in my edit – Robbie Milejczak Dec 05 '17 at 14:26
  • `window.addEventListener('wheel', (e) => { this.scroll(e.wheelDelta);})` – Robbie Milejczak Dec 05 '17 at 14:26
  • I thought you meant an arrow function! I've added this and it works a treat! If you update your answer I will mark it correct. – Filth Dec 05 '17 at 14:28
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/160522/discussion-between-filth-and-robbie-milejczak). – Filth Dec 05 '17 at 14:43
6

The following should work fine for you:

componentDidMount(){
  let slickListDiv = document.getElementsByClassName('slick-list')[0]
  slickListDiv.addEventListener('wheel', event => {
    event.preventDefault()
    event.deltaY > 0 ? this.slider.slickNext() : this.slider.slickPrev()
  })
}

You should initialize the component like this:

<Slider {...settings} ref={slider => this.slider = slider.innerSlider}>
...
</Slider>
lavee_singh
  • 1,379
  • 1
  • 13
  • 21
1

I use the following code in my CustomSlider component:

  constructor(props) {
    super(props);
    this.handleWheel = this.handleWheel.bind(this);
  }

  componentDidMount() {
    ReactDOM.findDOMNode(this).addEventListener('wheel', this.handleWheel);
  }

  componentWillUnmount() {
    ReactDOM.findDOMNode(this).removeEventListener('wheel', this.handleWheel);
  }

  handleWheel(e) {
    e.preventDefault();
    e.deltaY > 0 ? this.slider.slickNext() : this.slider.slickPrev();
  }

Component initialization

 <Slider ref={slider => this.slider = slider}>
   ...
 </Slider>
1

With hooks

const sliderRef = createRef();
const scroll = useCallback(
    y => {
      if (y > 0) {
        return sliderRef?.current?.slickNext(); /// ? <- using description below 
      } else {
        return sliderRef?.current?.slickPrev();
      }
    },
    [sliderRef]
  );
 useEffect(() => {
    window.addEventListener("wheel", e => {
      scroll(e.deltaY);
    });
  }, [scroll]);

I used optional chaining from typescript connected with babel plugins, but you can use verification like:

 sliderRef.current && sliderRef.current.slickNext() 
0

I was able to get scrolling to work in a function component that reference the Slider component (react-slick JS library) using hooks (useRef to obtain a reference to the Slider component and useEffect to add and remove a listener (scroll function) to the wheel event).

const myComponent () => {

 const settings = {
    dots: true,
    slidesToShow: 1,
    slidesToScroll: 1,};

const slider = useRef(null);

function scroll(e){
    if (slider === null)
        return 0;

    e.wheelDelta > 0 ? (
        slider.current.slickNext()
    ) : (
        slider.current.slickPrev()
    );

};

useEffect(() => {
    window.addEventListener("wheel", scroll,true);

    return () => {
        window.removeEventListener("wheel", scroll, true);
    };
}, []);

return (
 <Slider {...settings} ref={slider}>
 </Slider>
);
}

export default myComponent;
Dom
  • 1