A
A
Artur Galyaev2020-08-05 22:52:06
React
Artur Galyaev, 2020-08-05 22:52:06

How to add a scroll to a React element?

I'm making a chat component and I want it to immediately "scroll" down to the latest messages. Tried to do it with a ref, didn't help. The thing is that the element is shown with a delay (due to requests to the server) and the ref stops working. What to do?

const Chat = () => {
    const dispatch = useDispatch()
    const chatRef = useRef()
    const chat = useSelector(state => state.chat);
    const loading = useSelector(state => state.main.loading);
    useEffect(() => {
        dispatch(getChat())
    }, [])
    useEffect(() => {
        if(!loading && chat.messages) chatRef.current.scrollTo(0, 100)
    }, [chat])
  return (
    <div>
{loading ? 'loading':
        <div className="mt-3">
                <div>
                    <div ref={chatRef} style={{height: '65vh', overflow:'auto'}} >
                        {chat.messages.map(item => 
                                <p>{item.username}: {item.text}</p>
                        )}
                    </div>
                </div>
        </div>
            }
</div>
  )
}	

export default Chat;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sakhnyuk, 2020-08-06
@art5455

Add a loading effect to the dependencies and go down to the height of the scroll.
Make sure chat.messages is falsy (if it's an empty array, then check as chat.messages.length).

useEffect(() => {
        if (!loading && chat.messages && chat.messages.length) {
            chatRef.current.scrollTop = chatRef.current.scrollHeight
        };
    }, [chat, loading])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question