hackerex
hackerex

Reputation: 3

React owl.carousel $ not defined

I have created app using create-react-app. I have imported module jquery in component and also owl.carousel but why it is showing error.

Here is the Component Code

import React,{Component} from 'react';

import $ from '../../../node_modules/jquery/dist/jquery.min'
import '../../../node_modules/owl.carousel/dist/owl.carousel'

import '../../../node_modules/owl.carousel/dist/assets/owl.carousel.min.css'

class Header extends Component{

    componentDidMount() {
    }

    render(){
        return(
            <div className="owl-carousel">
                <div>Content 1</div>
                <div>Content 2</div>
                <div>Content 3</div>
                <div>Content 4</div>
                <div>Content 5</div>
                <div>Content 6</div>
                <div>Content 7</div>
            </div>
        )
    }
}

Cannot read property of undefined. Error screenshot

Upvotes: 0

Views: 5634

Answers (1)

azium
azium

Reputation: 20624

You can see from the screenshot that Owl is expecting zepto or jQuery to be on window. When you import something it's only available in the scope of that module, not on window.

There are several ways to fix this:

Option 1: include jQuery in your public/index.html I would recommend using a cdn

Option 2: import jQuery, put in on window, then import owl

// note: you don't need the whole path to node_modules.. just the package name
import jQuery from 'jquery'

window.jQuery = jQuery

// dynamically require owl
require('owl.carousel')

note: import statements need to go before require statements

Option 3 (Best option):

Just use the react-owl-carousel package, or use another carousel package that doesn't need jQuery. Either way importing jQuery into react to use a non-react package is unnecessary these days.

Upvotes: 3

Related Questions