1

I'm trying to use jquery.scrollto on my react app but cannot seem to use it correctly.

I installed it via npm

>npm install jquery.scrollto
+ jquery.scrollto@2.1.2
added 1 package in 5.316s

but when I try to use it I get a typeError

Uncaught TypeError: $(...).scrollTo is not a function

Here's the code inside the application :

var $ = require('jquery')
require('jquery.scrollto')

$('#home').on('click',function(){
  $(window).scrollTo('#home', 1000);
})    

and here's my package.json :

{
  "name": "portfolio",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "jquery": "^3.3.1",
    "jquery.scrollto": "^2.1.2",
    "react": "^16.4.2",
    "react-dom": "^16.4.2",
    "react-scripts": "1.1.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Am I missing something ? Thanks a lot.

Hallemon
  • 161
  • 1
  • 14
  • React uses a "Virtual DOM" which jQuery can not "read" from - so you should do it like the solution in this question: https://stackoverflow.com/questions/43441856/reactjs-how-to-scroll-to-an-element – davbuc Sep 06 '18 at 22:09
  • the plugin you're using uses the syntax within the onclick function. Did you attempt just $(window).scrollTo( '#home", 1000)? – Rachel Gallen Sep 07 '18 at 01:02
  • @RachelGallen Yes I have, and I wouldn't work. However I found where was the problem, apparently when used with react, jquery.scrollto does not need to be nested in jquery but can be used independently. I'll post the whole process below. – Hallemon Sep 07 '18 at 14:55

1 Answers1

1

After several tries, I found out how to make it work.

I was requiring scrollto as such : require('jquery.scrollto') and then calling it via the jquery's $(). Apparently it is not the way to go when scrollTo is installed via npm. What I did was the following :

var $ = require('jquery');
var scrollTo = require('jquery.scrollto');

// inside react's componentDidMount : 
$('#testbutton').on('click',scrollto(0,500))

I had no idea that scrollto didn't need to be nested in jquery.

Also, I realised it was innefective to use string refs, I advice people reading this thread to visit ReactJS how to scroll to an element for additional informations. Thanks and credits to @davidbucka

Hallemon
  • 161
  • 1
  • 14