Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a Jquery function into React

I have this swipe function I created with swipejs.org / html that was originally for someone else but am using it in my own project.

I first made a functioning version of what I want to do in HTML & Jquery which is here on jsfiddle: https://jsfiddle.net/sbfield/nojhqbtx/1/

After this, I created a react component for this:

import React from 'react'


export default function CompareBox() {

  var element = document.getElementById('mySwipe');


  window.mySwipe = new Swipe(element, {
    startSlide: 0,
    draggable: true,
    autoRestart: false,
    continuous: false,
    disableScroll: true,
    stopPropagation: true,
    callback: function (index, element) { },
    transitionEnd: function (index, element) { }
  });


  return (
    <>
      <div id="myContainer">
        <div id="mySwipe" class="swipe">
          <div className="swipe-wrap">
            <div>
              <div className="red">
              </div></div>
            <div><div className="grey"></div></div>
          </div>
        </div>
      </div>
    </>
  )
}

I've added the CDN for swipejs into my React index.html file:

  <script crossorigin src="https://cdn.jsdelivr.net/gh/lyfeyaj/swipe/swipe.js"></script>
  <script crossorigin src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

However, it's not working into my React project

Error:

./src/components/CompareBox.jsx
  Line 9:24:  'Swipe' is not defined  no-undef

I've installed swipejs as an npm package https://www.npmjs.com/package/swipejs but when I try to use import { Swipe } from 'swipejs' there is a new error:

TypeError: swipejs__WEBPACK_IMPORTED_MODULE_1__.Swipe is not a constructor

This is the first time I've added jquery into a React project, so I'm not sure where to go next. Any help is appreciated.

like image 807
Noble Polygon Avatar asked Apr 16 '26 21:04

Noble Polygon


1 Answers

Try add jQuery to your project, do this

npm i jquery --save

and then import into your component

import $ from 'jquery'

and then place your jquery code in componentDidMount() like this, just as an example

  componentDidMount() {
    this.$el = $(this.el);
    this.$el.circlize({
      stroke: 15,
      percentage: 45,
      usePercentage: true,
      background: "#1abc9c",
      gradientColors: ["#ffa500", "#ff4500", "#ffa500"]
    });
  }

for more help, click here React/ReactJS: Using a jQuery Plugin with React

like image 52
Muhammad Usama Rabani Avatar answered Apr 18 '26 12:04

Muhammad Usama Rabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!