Skip to content

Instantly share code, notes, and snippets.

@watzon
Created March 17, 2023 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watzon/75af819314250814fafd97ce623d890e to your computer and use it in GitHub Desktop.
Save watzon/75af819314250814fafd97ce623d890e to your computer and use it in GitHub Desktop.
import { useState } from "preact/hooks";
export interface MessageInputProps {
onSubmit: (message: { content: string; image: string | null }) => void;
}
const MessageInput = ({ onSubmit }: MessageInputProps) => {
const [message, setMessage] = useState<string>("");
const [image, setImage] = useState<string | null>(null);
const handleFileChange = (event: Event) => {
const target = event.target as HTMLInputElement;
const file = target.files ? target.files[0] : null;
if (file) {
const reader = new FileReader();
reader.onload = (event) => {
const target = event.target as FileReader;
setImage(target.result as string);
};
reader.readAsDataURL(file);
}
};
const handleSubmit = (event: Event) => {
console.log("Hello world");
event.preventDefault();
onSubmit({ content: message.trim(), image });
setMessage("");
setImage(null);
};
const handleTextAreaChange = (event: Event) => {
const target = event.target as HTMLTextAreaElement;
setMessage(target.value);
};
return (
<div className="flex items-center space-x-4">
<textarea
className="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"
rows={2}
value={message}
onChange={handleTextAreaChange}
>
</textarea>
<label className="bg-indigo-500 text-white px-4 py-2 rounded-md cursor-pointer">
<input
type="file"
className="hidden"
accept="image/*"
onChange={handleFileChange}
/>
Attach
</label>
<button
type="button"
onClick={handleSubmit}
className="bg-indigo-600 text-white px-4 py-2 rounded-md"
>
Send
</button>
</div>
);
};
export default MessageInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment