1

I use browserify to build react components. And I need to use npm jquery-scrollto plugin https://www.npmjs.com/package/jquery-scrollto, but it doesn't work.

I don't understand how It can be used? Maybe

var $            = require('jquery');
var ScrollTo     = require('jquery-scrollto');

ScrollTo('#myelem');

Or something else...

victorkt
  • 13,992
  • 9
  • 52
  • 51
Tony
  • 566
  • 2
  • 5
  • 16
  • Hi , by any chance, did you figure out how to use jquery-scrollto in react ? I am facing the same problem where the error is shown scrollTo is not a function – Haris Mehmood Apr 27 '17 at 10:40

2 Answers2

0

Even if using browserify, jquery.scrollTo is still a jQuery plugin and should be called as $(...).scrollTo(...).

You still need to require it so it adds itself to jQuery.fn, something like this:

var $            = require('jquery');
require('jquery-scrollto');

$(window).scrollTo('#myelem', 1000);

Visit the Github page for documentation.

Ariel Flesler
  • 612
  • 1
  • 4
  • 13
0

There are two things the scrollTo needs: the thing to scroll (such as window or a div) and the target (#myelem in your example). The thing you want to scroll should be a jQuery object, which is why @Ariel Flesler advised to wrap it like this: $(thingToScroll).

Before you get to that point, if you're using Browserify, you'll need to correctly import jQuery and the plug-in. I Googled how to do this and came away more confused- does not look simple. Here's an SO post that looks like it's about that: Configure a generic jQuery plugin with Browserify-shim?

But I would suggest not even trying, since using that plug-in with React is probably more trouble than it's worth. If you just want to scroll window it may not be so bad, but if you want to scroll elements of the page, you will have to go back and forth between React's virtual DOM and the real DOM on the page using refs http://facebook.github.io/react/docs/working-with-the-browser.html. If you've decided to go with React, you're much better off just using JavaScript and the standard DOM API instead of jQuery. An advantage of jQuery is that it does the work of papering over inconsistencies and bugs in browsers' DOM implementations. React also does some of this work for for you behind-the-scenes.

So, the short version is that it will be easiest to pick whether you want to use React or use jQUery. If go no-jQuery, the MDN browser API documentation might help:

https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

Community
  • 1
  • 1
Max Heiber
  • 14,346
  • 12
  • 59
  • 97