hard time understanding how the handlekey function work on onKeydown in React

Viewed 17

I create a simple to do list that have add button and have a function inside OnKeydown which allow to add by pressing Enter. But I'm still confused how this function work.

const Handlesubmit = (e) =>{
      e.preventDefault()
      setTodo([...todo, {text: input, id: Math.random() * 1000}])
  }

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      Handlesubmit(e)
    }
  } 
 return (
    <div className="App">
      <input type="text" onKeyDown={handleKeyDown} value={input} onChange={Handleinput}/>
      <button onClick={Handlesubmit}>Add</button>
      {todo.map(todos => (
        <div key={todos.id}>
       <p> {todos.text} </p> 
       </div>
       ))
      }
    </div>
  );

The part that i don't understand is why we need Handlesubmit(e) in the handleKeyDown. Why handlesubmit() wont' work without e which is event in the handlkeyDown function?

const handleKeyDown = (e) => {
        if (e.key === 'Enter') {
           Handlesubmit(e)
        }
      }

if without e like

const handleKeyDown = (e) => {
        if (e.key === 'Enter') {
          Handlesubmit()
        }
      } 

it show an error saying

e is not defined

in my handlesubmit function.

  const Handlesubmit = (e) =>{
      e.preventDefault() <<< e is not defined in here
      setTodo([...todo, {text: input, id: Math.random() * 1000}])
  }

can someone explain to me?

0 Answers
Related