Home > Enterprise >  Set the focus to input after submitting the form
Set the focus to input after submitting the form

Time:05-20

After clicking on Enter, the focus returns to the input. If I press the button, the focus does not return. Please tell me how to make the focus return to the input after pressing the submit button.

  const setTodo = (event) => {
    setNewTodo(event.target.value)
  }

  const handleSubmit = (event) => {
    event.preventDefault()
  }

  const addTodoByEnter = (event) => {
    if (event.key === 'Enter') {
      if (newTodo.trim() !== '') {
        const currentTodo = { id: Date.now(), text: newTodo.trim(), complited: false, order: todos.length   1 }
        setTodos([...todos, currentTodo])
        setNewTodo('')
      }
    }
  }

  const addTodoByClick = () => {
    if (newTodo.trim() !== '') {
      const currentTodo = { id: Date.now(), text: newTodo.trim(), complited: false, order: todos.length   1 }
      setTodos([...todos, currentTodo])
      setNewTodo('')
    }
  }

<div className="input">
          <form className="input__form" action="" onSubmit={handleSubmit}>
            <input
              className="input__add"
              type="text"
              maxLength={180}
              value={newTodo}
              onKeyDown={(event) => addTodoByEnter(event)}
              onChange={setTodo}
              autoFocus />
            <button className="input__img" type="submit" onClick={addTodoByClick}></button>
          </form>
        </div>

CodePudding user response:

I think you can use DOM.focus() and useRef() to handle what you looking for:

const inputRef = useRef()

const setTodo = (event) => {
    setNewTodo(event.target.value)
  }

  const handleSubmit = (event) => {
    event.preventDefault()
  }

  const addTodoByEnter = (event) => {
    if (event.key === 'Enter') {
      if (newTodo.trim() !== '') {
        const currentTodo = { id: Date.now(), text: newTodo.trim(), complited: false, order: todos.length   1 }
        setTodos([...todos, currentTodo])
        setNewTodo('')
      }
    }
  }

  const addTodoByClick = () => {
    if (newTodo.trim() !== '') {
      const currentTodo = { id: Date.now(), text: newTodo.trim(), complited: false, order: todos.length   1 }
      setTodos([...todos, currentTodo])
      setNewTodo('')
      inputRef.current?.focus();
    }
  }

<div className="input">
          <form className="input__form" action="" onSubmit={handleSubmit}>
            <input
              ref={inputRef}
              className="input__add"
              type="text"
              maxLength={180}
              value={newTodo}
              onKeyDown={(event) => addTodoByEnter(event)}
              onChange={setTodo}
              autoFocus />
            <button className="input__img" type="submit" onClick={addTodoByClick}></button>
          </form>
        </div>
  • Related