4

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 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

7 Comments

OK error is gone, but, why new error 'Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.'
@Pranav I don't see that error in your or my sandbox. Is that something to do with textMessages or updating that state? It's the only array I see. Did that error just appear after fixing the ref access or are you doing something to trigger it? I see that you've an useEffect that loads some messages from local storage, this can possibly set your state to undefined if there is no localStorage with that key.
@Pranav Yeah, I suspected as much and tried the "send message" button. I see you load from localStorage, but if the localStorage has never been used you set your textMessage state to undefined. Also, when saving to localStorage you need to JSON.stringify it, and then JSON.parse it when reading back out.
@Pranav I'm not quite sure what you mean by "last message is going so deep", but if you are referring to the messages list going behind/underneath the input "bubble" yes, this seems very much CSS. If not this can you clarify what is "deep"?
|

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.