0

I'm trying to make this simple component where I type a message in the input box and the component returns the message in a list underneath the input field. However when I click the submit button the only thing that appears below is a blank bullet point

import React, { useState } from 'react'

function Form(props) {
    const [message, setMessage] = useState([])

    const addMessageHandler = (event) => {
        event.preventDefault()

        const data = new FormData(event.target);

        const _data = data.get('input')

        setMessage([...message, { id: message.length, value: _data }])
    }

    return (
        <div>
            <form onSubmit={addMessageHandler} id='input'>
                <label>Type a Message</label>
                <input type='text'></input>
                <button type='submit'>Submit</button>
            </form>

            <ul>
                {
                    message.map(msg => (
                        <li key={msg.id}>{msg.value}</li>
                    ))
                }
            </ul>
        </div>
    )
}

export default Form
1
  • Are you sure your variable _data has the expected value of the input field? Commented Jul 27, 2022 at 12:49

1 Answer 1

1

All ways add "id" & "name" attributes to input fields.

  <label htmlFor="chat_box">Type a Message</label>
  <input type='text' id="chat_box" name="chatbox_input" />

now you can access input elements in e.currentTarget.elements, just make sure you have give unique names to input tags.

const addMessageHandler = (event) => {
  event.preventDefault()
  setMessage((message) => [...message, { id: message.length, value:  e.currentTarget.elements['chatbox_input'].value }])
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.