Stefanvdk
Stefanvdk

Reputation: 155

Chessboardjs NPM package in react, referenceerror $ is not defined

I am trying to use https://www.npmjs.com/package/chessboardjs package. I wrote simple react component to render the board, but it throws an error in the chessboardjs module: ReferenceError: $ is not defined. The component code:

import React, { Component } from 'react';
import Chess from 'chessboardjs';

export default class ChessBoard extends Component {
    render() {
        return (
            <div>
                <div id="chessboard" style={{"width": "400px"}}></div>
            </div>
        )
    }

    componentDidMount() {
        var board = Chess('chessboard');
    }
}

I already tried installing the JQuery npm package and import that in the ChessBoard component but it didn't work unfortunately.

Is there a way to fix this?

Upvotes: 0

Views: 1184

Answers (2)

Sherfin Shamsudeen
Sherfin Shamsudeen

Reputation: 1

Not sure if this is the best way,

import React, { Component } from 'react';
import $ from 'jquery'
import Chess from 'chessboardjs';

window.$ = $
window.jQuery = $

export default class ChessBoard extends Component {
    render() {
        return (
            <div>
                <div id="chessboard" style={{"width": "400px"}}></div>
            </div>
        )
    }

    componentDidMount() {
        var board = Chess('chessboard');
    }
}

Upvotes: 0

Soso hu
Soso hu

Reputation: 31

I think you should import the $, jQuery, window.jQuery variables into all modules. If you use webpack1,you can try by this:

providePlugin = new webpack.ProvidePlugin({
    $: "jquery",
    jQuery: "jquery",
    "window.jQuery": "jquery"
  }),

Upvotes: 3

Related Questions