4

I am adding the Scroll to top div in Footer section. After clicking on the scroll top icon it will go the top of page

After Clicking on the Scroll to top it will go the top of page

Here is my code

import React from 'react';

class ScrollTop extends React.Component {
    render() {
        return (
            <div className="scrolltop">
                <i className="fa fa-angle-up" />
            </div>
        );
    }
}

export default ScrollTop;
1
  • 1
    React is just JavaScript. Not everything has to be done the "React way". Commented Aug 20, 2019 at 12:55

4 Answers 4

10

Just use vanilla javascript

import React from 'react';

class ScrollTop extends React.Component {
    render() {
        return (
            <div className="scrolltop" onClick={() => window.scrollTo({top: 0, behavior: 'smooth'})}>
                <i className="fa fa-angle-up" />
            </div>
        );
    }
}

export default ScrollTop;
Sign up to request clarification or add additional context in comments.

1 Comment

The component is stateless, so a function component will do: function ScrollTop(){return(<div ... />)}
2

may be use this function

handleScroll=()=>{
    window.scrollX(0);
    // or 
    window.scroll({top:0,behavior:'smooth'})

}

Comments

0
  1. Before this code, you must install react-router.

  2. npm i react-router-dom

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

export default function scrollTop() {
    const { pathname } = useLocation();

    useEffect(() => {
        window.scrollTo(0, 0);
    }, [pathname])

    return null;
}

Comments

0
  1. Install react-scroll from https://www.npmjs.com/package/react-scroll

  2. Import and use in your component like below(ES6 style):

import { Link, animateScroll as scroll } from "react-scroll";

<Link 
to="/" 
className='someDiv'
onClick={()=>scroll.scrollToTop()}>
Logo
</Link>
  1. Click on the element(here Logo) to see the magic.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.