Unable to use OwlCarousel in my React Project

112 views Asked by At

I don't have expertise in using React Libraries and Packages. Need some help in understanding the issue I'm facing. I'm using React OwlCarousel for my Project but it shows the error:

"Cannot read properties of undefined (reading 'fn')"

Here is my "App.js":

import React from "react";
import OwlCarousel from "./OwlCarousel";

const App = () => {
  return (
    <div className="App">
      <OwlCarousel />
    </div>
  );
};

export default App;

And following is my "OwlCarousel.js":

import React, { useEffect } from "react";
import "owl.carousel/dist/assets/owl.carousel.css";
import "owl.carousel/dist/assets/owl.theme.default.css";
import $ from "jquery";
import "owl.carousel";

const OwlCarousel = () => {
  useEffect(() => {
    $(".owl-carousel").owlCarousel({
      items: 3,
      loop: true,
      margin: 10,
      autoplay: true,
      autoplayTimeout: 2000,
      autoplayHoverPause: true
    });
  }, []);

  return (
    <div className="owl-carousel">
      <div className="item">
        <img src="https://via.placeholder.com/200" alt="Item 1" />
      </div>
      <div className="item">
        <img src="https://via.placeholder.com/200" alt="Item 2" />
      </div>
      <div className="item">
        <img src="https://via.placeholder.com/200" alt="Item 3" />
      </div>
      <div className="item">
        <img src="https://via.placeholder.com/200" alt="Item 4" />
      </div>
      <div className="item">
        <img src="https://via.placeholder.com/200" alt="Item 5" />
      </div>
    </div>
  );
};

export default OwlCarousel;

This is react codesandbox example's link: https://codesandbox.io/s/owlcarouseldemo-llsndh

1

There are 1 answers

0
Luu Hoang Bac On

You can't just use import "owl.carousel"; like that. It doesn't work that way.

If you have to use the owl carousel, I suggest you use react-owl-carousel

Here is an example of how to use it. But the owl carousel has been dead for 5 years already. I suggest you don't use it. You can use something more friendly with ReactJS like SwiperJS. They have really nice documentation and demos, so you can easily use it.