0

I am making a basic todo list with React and right now, it works when I press a button with text in the text field. I am trying to make it work so when I press enter on the input field, it also works. The function itself works when I press the button, I just want some sort of "onEnter" instead of "onClick" to submit the field as well. Here is what I have right now...

import React, { useState, useEffect } from 'react'

function handleSubmit(event) {
    // event logic here, code already works.
    // takes the text in the input field and adds to list
    // works on button press.
}

export function TodoInput() {
    return (
        <div>
            <input onSubmit={handleSubmit} id="todoInput" type="text" />
            <button className="submitButton" onClick={handleSubmit}>Add to Todo</button>
        </div>
    )
}
  • 2
    You can simply wrap your input in a
    , move the `onSubmit` handler to the form tag, then call `e.preventDefault();` in the handler function. This uses the browser's standard behavior and is better practice than manually assigning an onkeypress listener because it will definitely work in every environment (note that this solution is not React specific)
    –  Oct 17 '20 at 08:35
  • wrap your input field inside of the form tag and and give onSubmit = { // code } . Then you don't need the submit button as well.
    input here....
    – Badri Paudel Oct 17 '20 at 08:38

0 Answers0