Home > Blockchain >  How to pass <form> data to an object array in React
How to pass <form> data to an object array in React

Time:07-27

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

CodePudding user response:

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 }])
}
  • Related