nanquim
nanquim

Reputation: 1924

Reactjs - Can't type in text field

I know there are similar questions, but none of them helped me. It's probably something silly, but I can't find out what it is.

I'm following a tutorial and code above don't let me write into inputs. It works when I remove spread operator, but then only last input is saved to state

function FormContato() {

    const [valores, setaValores] = useState({
        name: '',
        email: '',
        mensagem: ''
    })

    const atualizaCampo = e => {
        setaValores({
            ...valores,
            [e.target.name]: e.target.value
        })
    }

    const enviar = e => {
        e.preventDefault()
        console.log('valores\n')
        console.log(valores)
    }

    return (
        <div className="form-externo p-3 d-flex flex-column">
            <h3>Contato</h3>
            <div id="form-interno">
                <form onSubmit={e => enviar(e)}>
                    <div className="form-group">
                        <label for="name">Nome: *</label>
                        <input
                            value={valores.name}
                            onChange={(e) => atualizaCampo(e)}
                            type="text"
                            className="form-control"
                            id="name"
                            required
                        />
                    </div>
                    <div className="form-group">
                        <label for="email">Email: *</label>
                        <input
                            value={valores.email}
                            onChange={e => atualizaCampo(e)}
                            type="email"
                            className="form-control"
                            id="email"
                            required />
                    </div>
                    <div className="form-group">
                        <label for="message">Mensagem</label>
                        <textarea
                            value={valores.mensagem}
                            onChange={e => atualizaCampo(e)}
                            type="text"
                            className="form-control"
                            id="message"
                            rows="3">
                        </textarea>
                    </div>
                    <button className="btn btn-enviar">Enviar</button>
                </form>
            </div>
        </div>
    )
}

Upvotes: 1

Views: 120

Answers (1)

lluisrojass
lluisrojass

Reputation: 439

An event's target is a reference to the element which dispatched the event. The inputs here have no "name" property.

https://developer.mozilla.org/en-US/docs/Web/API/Event/target

Upvotes: 2

Related Questions