Joachim Lous
Joachim Lous

Reputation: 1541

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.

Upvotes: 7

Views: 20802

Answers (2)

Farhad
Farhad

Reputation: 4181

you can use:

document.getElementById("ElementName").focus();

Final code here:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<script>
function change() {
    document.getElementById("two").focus();
}
</script>
</head>



<body>
    <input type="radio" name="name" id="name" onchange="change()" /> 

    <input type="text" name="one" id="one" /> 
    <input type="text" name="two" id="two" /> 
</body>
</html>

Upvotes: 0

Andreyco
Andreyco

Reputation: 22862

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();
}

Upvotes: 2

Related Questions