Much like the ecommerce app here, I have wanted to understand the mechanics behind a chat app for a long time, and again thought it best to start with a rather simplistic app before going on to learn more professioanl approaches to a solution. This app is, fortunately, amazingly simple. Users must sign in using Google, and are then granted access to a welcome-allcomers chatroom. Let's have a look at the code.

The main app is beautiful in its simplicity (as you would expect for such a simple app), with the main content displayed being dependent upon whether the user is signed in or not.

<div className="App">
    <header className="App-header">
        <h1>Messenger</h1>
        <SignOut />
    </header>
    <section>
        {user ? <ChatRoom/> : <SignIn />}
    </section>
</div>

The actual ChatRoom component is connected to a Firebase collection. We collect messages from Firebase using the following line:

const [messages] = useCollectionData(query, { idField: 'id' });

And then if any messages exist we map through them and pass them down to a ChatMessage component:

{messages && messages.map(msg => <ChatMessage key={msg.id} message={msg}/>)}

The ChatMessage component receives the user id and photo from Firebase's Auth function, and attributes a class to the message dependant upon whether the message was sent or received.

function ChatMessage(props) {
    const { text, uid, photoURL } = props.message;
    const messageClass = uid === auth.currentUser.uid ? 'sent' : 'received';
    return (
        <>
        <div className={`message ${messageClass}`}>
            <img src={photoURL} alt={photoURL}/>
            <p>{text}</p>
        </div>
        </>
    )
}