diff --git a/2-copy-of-code/lesson-04/chatbot.html b/2-copy-of-code/lesson-04/chatbot.html index ea863df..3f038fc 100755 --- a/2-copy-of-code/lesson-04/chatbot.html +++ b/2-copy-of-code/lesson-04/chatbot.html @@ -196,15 +196,27 @@ ); } - function ChatMessages({ chatMessages }) { - const chatMessagesRef = React.useRef(null); + // To use a function as a hook, the function name must + // start with "use". + function useAutoScroll(dependencies) { + // It's highly recommend to rename this to something + // more generic like containerRef. This will make the + // code make more sense if we ever reuse this code in + // other components. + const containerRef = React.useRef(null); React.useEffect(() => { - const containerElem = chatMessagesRef.current; + const containerElem = containerRef.current; if (containerElem) { containerElem.scrollTop = containerElem.scrollHeight; } - }, [chatMessages]); + }, dependencies); + + return containerRef; + } + + function ChatMessages({ chatMessages }) { + const chatMessagesRef = useAutoScroll([chatMessages]); return (