Skip to content

Instantly share code, notes, and snippets.

@ajeetkumarrauniyar
Last active August 17, 2024 16:20
Show Gist options
  • Select an option

  • Save ajeetkumarrauniyar/4ce510f8bb8b4a03574a69a748942150 to your computer and use it in GitHub Desktop.

Select an option

Save ajeetkumarrauniyar/4ce510f8bb8b4a03574a69a748942150 to your computer and use it in GitHub Desktop.
Chat App in TypeScript using
"use client";
import { FormEvent, useState } from "react";
interface IMessages {
message: string;
userId: string;
}
export default function Home() {
const [messages, setMessages] = useState<Array<IMessages> | undefined>([]);
const [message, setMessage] = useState<string>();
const onChange = (e: any) => {
setMessage(e.target.value);
};
const submit = (e: FormEvent) => {
e.preventDefault();
if (message && messages) {
setMessages([...messages, { userId: "my", message }]);
setMessage("");
}
};
return (
<main className="size-full flex items-center">
<div className="bg-black h-[90%] w-[80%] mx-auto flex border-2 rounded-lg flex-col justify-between p-1 gap-2">
<div className="w-full border-2 rounded-lg h-full p-2 flex flex-col overflow-scroll s">
{messages?.map((e) => (
<div className="pb-2">
<p
className={`bg-slate-600 ${
e.userId === "my" ? "float-right" : "float-left"
} px-2 rounded-md`}
>
{e.message}
</p>
</div>
))}
</div>
<form
className="flex justify-center items-center gap-2"
onSubmit={submit}
>
<input
type="text"
className="bg-transparent border-2 rounded-full px-3 h-12 w-full outline-none"
placeholder="message..."
onChange={onChange}
value={message}
/>
<button
type="submit"
className="bg-white text-black font-medium rounded-full w-20 h-12 text-center"
>
Send
</button>
</form>
</div>
</main>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment