Dils Matchanov
Dils Matchanov

Reputation: 577

Make scroll to top button with animation in React

I wanna add button, by clicking on which page will be scrolled back to the top with animation. I know how to realize that using JQuery. I tried this code:

import React, { Component } from 'react';

import $ from 'jquery';

import goUpNarrrowImage from '../static/img/goUpNarrow.png';

class GoTopButton extends Component {
  constructor() {
    super();

    this.onclick = this.onclick.bind(this);
  }

  render() {

    return ( 
      <button>
        <img src={goUpNarrrowImage} style={{
          display: "inline-block",
          marginRight: "10px"
        }} />
        наверх
      </button>
    );
  }

  onclick() {
    $("html, body").animate({ scrollTop: 0 }, 1000);
  }
}

export default GoTopButton;

But when I click the button nothing happens.

Upvotes: 4

Views: 7657

Answers (2)

Miloš Janda
Miloš Janda

Reputation: 21

you can do it easily with react component like https://www.npmjs.com/package/react-scroll-up

<ScrollToTop showUnder={0} duration={1000} >
    <button>
        <img src={goUpNarrrowImage} style={{
          display: "inline-block",
          marginRight: "10px"
        }} />
    </button>
</ScrollToTop>

Upvotes: 2

Hemadri Dasari
Hemadri Dasari

Reputation: 34014

onclick is missing in button. So pass onclick to the button

<button onclick={this.onclick}>

Upvotes: 1

Related Questions