reactjsreact-scroll

react-scroll scrollToBottom not working when scroll to x does work


I am using react-scroll npm package from here: https://www.npmjs.com/package/react-scroll

Following their example, I have set up my code and I can get the onClick functions to work for scrolling a specific distance but the scrollToBottom still does not work.

I have also set up my code slightly differently than their example as this.scrollToBottom was throwing errors and so was React.createClass.

Header.js

import React from 'react'
import './Header.scss'
import { Link, DirectLink, Element, Events, animateScroll as scroll, scrollSpy, scroller } from 'react-scroll'


 
const Header = () => ({
  componentDidMount: function() {
    Events.scrollEvent.register('begin', function(to, element) {
      console.log('begin', arguments);
    });
 
    Events.scrollEvent.register('end', function(to, element) {
      console.log('end', arguments);
    });
 
    scrollSpy.update();
  },
  componentWillUnmount: function() {
    Events.scrollEvent.remove('begin');
    Events.scrollEvent.remove('end');
  },
  scrollToTop: function() {
    scroll.scrollToTop();
  },
  scrollToBottom: function() {
    scroll.scrollToBottom();
  },
  handleSetActive: function(to) {
    console.log(to);
  },

  render: function() {
    return (
        <div className="Header">
            <div className="Header-div1">
                <h3 className="Header-div1__name">Caleb Middleton</h3>
            </div>
            <div className="Header-div2">
                <p className="Header-div2__About margin-right" onClick={() => scroll.scrollToBottom}>About</p>
                <p className="Header-div2__Skills margin-right" onClick={() => scroll.scrollTo(500)}>Skills</p>
                <p className="Header-div2__Projects margin-right" onClick={() => scroll.scrollTo(900)}>Projects</p>
            </div>
        </div>
    )
}
})

export default Header

Solution

  • You can use create-react-class if you want to retain this syntax.

    Run npm i create-react-class and include it in your project:

    const createReactClass = require('create-react-class');
    
    const Header = createReactClass({
      componentDidMount: function () {
        ...
    

    As for the scrollToBottom issues, currently you are just passing a function but not executing it. Refactor it like this:

    <p className="Header-div2__About margin-right" onClick={() => scroll.scrollToBottom()}>About</p>
    

    Edit still-brook-qhgmo

    Reference: https://reactjs.org/docs/react-without-es6.html


    Alternatively, you can convert your Header component to a class that extends React.Component and follow the syntax of a JavaScript class.