Answers for "scroll to top react router"

1

scoll to top on each route react

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

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

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

  return null;
}


function App() {
  return (
    <Router>
      <ScrollToTop />
      <App />
    </Router>
  );
}
Posted by: Guest on April-18-2021
6

scroll to top in react

componentDidMount() {
  window.scrollTo(0, 0)
}
Posted by: Guest on August-28-2020
2

scroll to top in react

useEffect(() => {
  window.scrollTo(0, 0)
}, [])
Posted by: Guest on August-28-2020
1

handling scrolling on react router transitions

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

function ScrollToTop({ history }) {
  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    }
  }, []);

  return (null);
}

export default withRouter(ScrollToTop);
Posted by: Guest on November-06-2020
0

scroll to top react

//__view.jsx
const ScrollTopView = (props) => {
	const { onScroll, onVisbile, visible } = props

	console.log(visible)
	if (typeof window === 'object') window.addEventListener('scroll', onVisbile)

	return (
		<>
			<div
				style={{
					position: 'fixed',
					bottom: 30,
					right: 30
				}}>
				<button
					className='btn btn-primary btn-small'
					onClick={onScroll}
					style={{ display: visible ? 'inline-block' : 'none', borderRadius: 5 }}>
					ScrollTop
				</button>
			</div>
			<h1 style={{ position: 'fixed', bottom: 25, left: '40%', display: visible ? 'inline-block' : 'none' }}>End Scroll</h1>
		</>
	)
}

export default ScrollTopView

// index.jsx
import ScrollTopView from './__view'
import { createElement, useState } from 'react'

const ScrollTop = () => {
	const [visible, setVisible] = useState(false)

	const onVisbile = () => {
		const scrolled = document.documentElement.scrollTop
		if (scrolled >= 600) setVisible(true)
		else if (scrolled <= 300) setVisible(false)
	}

	const onScroll = () => {
		if (typeof window === 'object') window.scrollTo({ top: 0, behavior: 'smooth' })
	}

	return createElement(ScrollTopView, {
		onScroll,
		onVisbile,
		visible
	})
}

export default ScrollTop
Posted by: Guest on June-25-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language