Getting error as 'Cannot read property scrollIntoView of null' when used scroll down code

Viewed 609

The above error frequently occurs with the following code

 const [consumerMessages, setConsumerMesssages] = useState([])

 const messagesEndRef = useRef(null);

 const scrollToBottom = () => {
        messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
      };
 
useEffect(() => {
        scrollToBottom()
      }, [consumerMessages]);

Following is the codesandbox link: https://codesandbox.io/s/sleepy-nobel-kt87m

Why this error is occuring and WHat could be the appropriate solution?

1 Answers

Issue

Basically on the initial render the ref hasn't been attached to the DOM node as the current ref value and so messagesEndRef.current isn't defined yet.

Solution

Use a null check:

messagesEndRef.current &&
  messagesEndRef.current.scrollIntoView({ behavior: "smooth" });

Or using Optional Chaining Operator (?.):

messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });

Demo

Edit getting-error-as-cannot-read-property-scrollintoview-of-null-when-used-scroll

Related