Skip to content

Scroll to the newest message ​

In a message list inside a scrollable box, new messages are appended below the visible area. On a new message, scroll the box to the end only if it was already at the end. A person who scrolled up to read older messages then keeps their position. To try it, send a few messages to the parrot, scroll up and send one more.

jsx
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';

// The fake agent repeats what you say.
const parrot = {
	name: 'Parrot',
	onMessage: (message) => `Polly says: ${message.text}! ${message.text}!`,
};

// The conversation in a box that scrolls and follows the newest message.
function MessageList({ messages }) {
	const list = useRef(null);
	const isAtBottom = useRef(true); // false while the person reads older messages

	// Scroll to a new message, unless the person scrolled up to read.
	useEffect(() => {
		if (isAtBottom.current) list.current.scrollTop = list.current.scrollHeight;
	}, [messages.length]);

	function handleScroll() {
		const box = list.current;
		isAtBottom.current = box.scrollHeight - box.scrollTop - box.clientHeight < 40;
	}

	return (
		<div ref={list} onScroll={handleScroll} style={{ height: 160, overflowY: 'auto', border: '1px solid #8888', padding: '0 8px' }}>
			{messages.map((message) => (
				<p key={message.id}><b>{message.fromMe ? 'You' : message.from}:</b> {message.text}</p>
			))}
		</div>
	);
}

export default function App() {
	// While building: the fake agent. In the webapp: useWorld()
	const { world: agent, error } = useWorld({ fake: { agent: parrot } });
	const [text, setText] = useState('');

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!agent) return <p>Connecting…</p>;

	function handleSubmit(event) {
		event.preventDefault();
		if (!text.trim()) return;
		agent.send(text);
		setText('');
	}

	return (
		<>
			<MessageList messages={agent.messages} />
			<form onSubmit={handleSubmit}>
				<input value={text} onChange={(event) => setText(event.target.value)} placeholder="Say something" />
				<button disabled={!agent.canSend}>Send</button>
			</form>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The fake agent repeats what you say.
const parrot = {
	name: 'Parrot',
	onMessage: (message) => `Polly says: ${message.text}! ${message.text}!`,
};

// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: parrot } });

// The conversation in a box that scrolls, and a box to write.
const list = document.createElement('div');
list.style.cssText = 'height: 160px; overflow-y: auto; border: 1px solid #8888; padding: 0 8px;';
const form = document.createElement('form');
const input = document.createElement('input');
input.placeholder = 'Say something';
const sendButton = document.createElement('button');
sendButton.textContent = 'Send';
form.append(input, sendButton);
document.body.append(list, form);

form.onsubmit = (event) => {
	event.preventDefault();
	if (!input.value.trim()) return;
	agent.send(input.value);
	input.value = '';
};

let isAtBottom = true; // false while the person reads older messages
list.onscroll = () => {
	isAtBottom = list.scrollHeight - list.scrollTop - list.clientHeight < 40;
};

let shownCount = 0;
agent.subscribe((node) => {
	sendButton.disabled = !node.canSend;
	if (node.messages.length === shownCount) return;
	shownCount = node.messages.length;
	list.replaceChildren(...node.messages.map((message) => {
		const line = document.createElement('p');
		const sender = document.createElement('b');
		sender.textContent = `${message.fromMe ? 'You' : message.from}:`;
		line.append(sender, ` ${message.text ?? ''}`);
		return line;
	}));
	// Scroll to a new message, unless the person scrolled up to read.
	if (isAtBottom) list.scrollTop = list.scrollHeight;
});
Live, on a fake world
Open

How it works ​

  • The box has a fixed height and overflow-y: auto. box.scrollTop = box.scrollHeight scrolls it to the end.
  • A scroll listener records whether the box is within 40 pixels of its end. A new message scrolls the box only in that case.
  • The trigger is a change in the number of messages. In React messages.length is the dependency of the effect. In plain JavaScript the code compares it with the last count it saw. Other changes of the world leave the scroll position unchanged.
  • scrollTop scrolls only the box and leaves the page of the webapp where it is.

See also ​

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.