Skip to content

Commit

Permalink
Add a new feature: Message Input
Browse files Browse the repository at this point in the history
  • Loading branch information
NazarMykolenko committed Oct 4, 2023
1 parent 3e6de56 commit 0700bfa
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/app/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
import { useEffect, useState } from 'react'
import Message from '@/components/Message'
import ThemeToggle from '@/components/ThemeToggle'
import InputMessage from '@/components/inputMessage'

const now = Date.now()

const MOCK_MESSAGES = [
{ sentAt: now - 1000 * 60 * 30, content: `...` },
{ sentAt: now - 1000 * 60 * 10, content: `Hello, i\'m a message! 😎` },
Expand All @@ -17,6 +19,13 @@ const MOCK_MESSAGES = [

export default function Home() {
const [mounted, setMounted] = useState(false)
const [messages, setMessages] = useState(MOCK_MESSAGES)

const addMessage = (newMessage) => {
const updatedMessages = [...messages, newMessage]
setMessages(updatedMessages)
console.log(updatedMessages)
}

useEffect(() => {
setMounted(true)
Expand All @@ -28,11 +37,13 @@ export default function Home() {

return (
<div className="flex flex-col gap-3 p-3">
{MOCK_MESSAGES.map(({ sentAt, content }, i) => (
{messages.map(({ sentAt, content }, i) => (
<Message key={i} sentAt={sentAt}>
{content}
</Message>
))}
<InputMessage addMessage={addMessage}></InputMessage>

<ThemeToggle />
</div>
)
Expand Down
45 changes: 45 additions & 0 deletions src/components/inputMessage.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import React, { useState } from 'react'

const InputMessage = ({ addMessage }) => {
const [message, setMessage] = useState('')

const handleMessageState = (e) => {
setMessage(e.target.value)
}

const handleSubmit = (e) => {
e.preventDefault()
// Handle the submission of the message (e.g., send it to a server, update the state, etc.)
console.log('Message submitted:', message)
const newMessage = {
sentAt: Date.now(),
content: message,
}
// Call the addMessage function to add the new message to the MOCK_MESSAGES array
addMessage(newMessage)
// Clear the input field after submitting the message
setMessage('')
}

return (
<div className="">
<form
onSubmit={handleSubmit}
className="flex items-center p-4 border-t border-gray-300"
>
<input
className="flex-1 p-2 mr-2 border border-grey-300 rounded"
type="text"
placeholder="Write a message"
value={message}
onChange={handleMessageState}
/>
<button className="bg-light flex border rounded p-1.5" type="submit">
Send
</button>
</form>
</div>
)
}
export default InputMessage
// flex-1 p-2 mr-2 border border-gray-300 rounded

0 comments on commit 0700bfa

Please sign in to comment.