简体   繁体   中英

React Hook Scroll to bottom of overflowing div on page load

I would like to scroll only an overflowing div while keeping the rest of the page at the normal starting position. Right now I'm getting a Cannot read property 'scrollIntoView' of null error when calling UseEffect

Code

import React, {Fragment, useEffect, useRef} from 'react';

const VideoPlayer = ({...foo...}) => {

   const chatRef = useRef(null)
       const scroll = () => {
           chatRef.current.scrollIntoView();
       }


   useEffect(() => {
           foo_function
           scroll()
       }, [foo_function]);

   }

   return (
   ...other-non-overflowing-div-content...

   <div>
      <div ref={chatRef}>
         <Link to={'/login'}>
           <p className='chat-sign-in'>Sign in to usechat</p>
         </Link>
       </div>
   </div>

   )
 }


在此处输入图片说明

You don't need the useRef . Try a callback ref instead. You can also pass it as a function with same signature.

<div ref={el => el.scrollintoview()}/>

Or

const cb = el => {
  foo();
  el.scrollintoview();
}

<div ref={cb}/>

Use useLayoutEffect instead useEffect

Here is a sandbox for a simple use-case

https://codesandbox.io/s/crazy-pasteur-44rfz?file=/src/App.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM