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.
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() .
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With