FredrikOseberg / react-chatbot-kit

MIT License
299 stars 139 forks source link

how to scroll to top of the chatbot message bubble rather than scroll down to the buttom? #76

Closed ysong10 closed 2 years ago

ysong10 commented 2 years ago

Some answers from our chatbot are very long. The chatbot scrolls automatically to the bottom so users have to scroll up to get to the top of the bubble and start reading. So can you tell me how to change the code to solve this, please?

ysong10 commented 2 years ago

I have solved this problem. In case other people met this problem, I will describe how I solved this problem in details. Basically, the problem is that every time there is message bubble coming or I input something, the two states (messages and input ) are changed, then useEffect is called

useEffect(() => {
    scrollIntoView();
  });

so chatContainerRef.current.scrollTop will be set to the bottom in the scrollIntoView() every time.

Solution:

  1. We need to add another method as below, so the scroll will not go to the bottom.
const scrollIntoViewNotToBottom = () => {
    setTimeout(() => {
      setInputValue("");
      // get div element by chatContainerRef.current
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight - 30;
    }, 50);
  };

and call this method in the method handleValidMessage

 const handleValidMessage = (userMsg) => {
    setState((state) => ({
      ...state,
      messages: [...state.messages, userMsg],
    }));
    scrollIntoViewNotToBottom();
  };
  1. because we just want the scroll not to the bottom when there is new message bubble coming, but when the users are ready to input something in the input box, we hope it will scroll up to the bottom because we want to make sure the users saw the whole message bubbles before they input. so we need to use different useEffect to differentiate the two states (messages and input ) as below:
    
    useEffect(() =>{
    scrollIntoViewNotToBottom();
    }, [messages])

useEffect(() => { scrollIntoView(); },[input]);