Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react: how to set focus from a click handler

My react-redux based form has a button that should reset the form and move focus back to the first input field.
Resetting the content is straight up redux state, but I'm having trouble with the focus.

autoFocus on the first field works only on the initial render. Is there any sane way to re-trigger it?

If I need to go with explicit element.focus(), where should I call it from? I'm using react-redux, but not redux-forms.

like image 544
Joachim Lous Avatar asked Apr 12 '16 13:04

Joachim Lous


People also ask

How do you set focus on click React?

To focus input when another element is clicked in React:Set the onClick prop on the other element. When the other element is clicked, focus the input, e.g. ref. current. focus() .

How do you focus the input field in a React functional component?

If you add React to an existing application and render a component into a detached element, React will call focus() before the browser is ready, and the input will not be focused when it gets added to the DOM. So, instead of depending on React to call focus() on the input, we are going to do it ourselves.

How do you move focus on next field when Enter is pressed in React?

To focus on the next field when pressing enter in React, we can set the onKeyDown prop of the inputs to a function that gets the next input and call focus on it. We have the handleEnter function that checks if the pressed key is Enter by checking the event.

How do you set focus on an element?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.


1 Answers

Do you keep some info in store to know which element should get focus on page load? Nope? Then why you should do that later?

Trigger element.focus() right after dispatching action - you don't need Redux to achieve this, nor Redux to store this state.

Pseudocode could look like this

onReset() {
  const action = {
    type: RESET_FORM,
  }
  dispatch(action);

  const element = getElement(); // propably read ref? Find element with [autoFocus] attribute in component?
  element.focus();
}
like image 166
Andreyco Avatar answered Sep 29 '22 08:09

Andreyco