37

I'm playing with React Hooks - rewriting a form to use hook concepts. Everything works as expected except that once I type any 1 character into the input, the input loses focus.

I guess there is a problem that the outside of the component doesn't know about the internal changes in the component, but how do I resolve this issue?

Here is the useForm Hook:

import React, { useState } from "react";

export default function useForm(defaultState, label) {
  const [state, setState] = useState(defaultState);

  const FormComponent = () => (
    <form>
      <label htmlFor={label}>
        {label}
        <input
          type="text"
          id={label}
          value={state}
          placeholder={label}
          onChange={e => setState(e.target.value)}
        />
      </label>
    </form>
  );

  return [state, FormComponent, setState];
}

Here is the component that uses the Hook:

function App() {
  const [formValue, Form, setFormValue] = useForm("San Francisco, CA", "Location");

  return (
    <Fragment>
      <h1>{formValue}</h1>
      <Form />
    </Fragment>
  );
}
Dragos Strugar
  • 1,314
  • 3
  • 12
  • 30

6 Answers6

49

While the answer by Kais will solve the symptoms, it will leave the cause unaddressed. It will also fail if there are multiple inputs - which one should autofocus itself on rerender then?

The issue happens when you define a component (FormComponent) inside the scope of another function which is called each render of your App component. This gives you a completely new FormComponent each time your App component is rerendered and calls useState. That new component is then, well, without focus.

Personally I would feel against returning components from a hook. I would instead define a FormComponent component, and only return state from useForm state.

But, a working example closest to your original code could be:

// useForm.js
import React, { useState } from "react";

// Define the FormComponent outside of your useForm hook
const FormComponent = ({ setState, state, label }) => (
  <form>
    <label htmlFor={label}>
      {label}
      <input
        type="text"
        id={label}
        value={state}
        placeholder={label}
        onChange={e => setState(e.target.value)}
      />
    </label>
  </form>
);

export default function useForm(defaultState, label) {
  const [state, setState] = useState(defaultState);

  return [
    state,
    <FormComponent state={state} setState={setState} label={label} />,
    setState
  ];
}
// App.js
import useForm from "./useForm";

export default function App() {
  const [formValue, Form] = useForm("San Francisco, CA", "Location");

  return (
    <>
      <h1>{formValue}</h1>
      {Form}
    </>
  );
}

Here's a sandbox

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 3
    This should be the answer. – Akash Sarkar Mar 30 '20 at 16:49
  • 1
    This really works! But I don't understand why. Please, can you explain why your solution is working? – Alfonso Tienda Nov 17 '20 at 12:38
  • 3
    @AlfonsoTienda It works because I moved the `FormComponent` outside of the `useForm` function, so it always points to the same object (contrary to a new object being created each call of `useForm` function). As a result, React no longer determines the whole DOM representation of `FormComponent` needs to be completely redrawn (object is same, no changes except value of input). Then, a flag "isFocused" or similar is **no longer lost during the redraw**. Remember, each time user inputs something, `useForm` is called by React with the updated state. At least thats how I understand it. – Kasparas Anusauskas Nov 18 '20 at 15:20
  • that's mind-blowing, tks. i have a similar issue, but I want to design the form with multiple inputs, so compose it with children inside other page componentes. is possible to pull something like that too? – João Melo Apr 30 '21 at 01:37
  • @KasparasAnusauskas I wanted to test something cause I have also issue when change something in Parent, my child app lose focus on input filed. I created working example, Parent render children and children can change state of parent. I expected when I set parent state from children it will cause parent to re-render child component and to lose focus at that moment. But I didn't lose focus in child component. Why that happened? Working example: https://codesandbox.io/s/parent-child-do-not-lose-focus-4f9cv – Predrag Davidovic May 17 '21 at 06:18
  • @PredragDavidovic your use case is OK (and actually how it's done, mostly) because you do not create the input / form component in your parent. So rerender doesn't create a new input / form component instance on each render. Here, I broke your example so you can see which the issue was in the original question (kind of, as it used a hook but core problem was the same): https://codesandbox.io/s/parent-child-do-not-lose-focus-forked-nqeqi – Kasparas Anusauskas May 19 '21 at 09:00
  • Hey, I understand what is problem, also fixed it in my app. What is intresting is if you reproduce this issues in codesandbox it will work perfectly but when you run it locally it will lose focus. THanks @KasparasAnusauskas – Predrag Davidovic May 19 '21 at 09:17
26

When you enter any text in input box. Parent Component is also re-rendering. So you need to make focus on input manually. For this, use autoFocus in input tag

<input
  type="text"
  id={label}
  value={state}
  placeholder={label}
  onChange={e => setState(e.target.value)}
  autoFocus
/>
Kais
  • 1,925
  • 3
  • 23
  • 35
7

The above answers didn't work for me. The solution that worked for me was much simpler and, for that reason, less obvious.

The Problem Essentially, the value that I was changing with the input was also being used for each key in a list of inputs.

Hence, when I updated the value the key would change and React would detect that it's different relative to the last key and create a new input in its place. As a new input it wouldn't focus on itself.

However, by using autoFocus it would automatically focus on the newly created input. But the issue wasn't fixed as it was obvious that the input was continually going through a cycle of un-focus and focus.

Here's an article demonstrating the problem.

The Fix

Update the key to an unchangeable value so React would have a stable reference to the list items. In my case I just updated it to the index. This is not ideal (React docs recommend using a stable ID), but in my situation it was okay because the order of the items won't change.

codeinaire
  • 1,682
  • 1
  • 13
  • 26
  • 1
    Thanks to this solution, I started thinking out of the box. Another problem that can manifest this way is senseless re-rendering by a parent component. It might not hurt to console.log down your component tree and make sure your re-rendering is only happening when you expect it to! I was fighting the problem at the wrong "level" of the component tree. – Jeff R May 27 '22 at 19:33
0

The first solution actually worked for me , initially the functional component which contained the text field was part of the main functional component , i was facing the same issue but when i extracted the text-field component into another page and imported it it worked fine This was my component

 <Paper >
      <div>
      <div style={{padding:'10px' ,display:'flex'}}  >       
      <inputstyle={{marginRight:'5px'}} value={val} onChange={(e)=>{setVal(e.target.value)}} />             
    </div>
    </div>
    </Paper>
mohantyArpit
  • 373
  • 4
  • 9
0

I had this problem when working with styled-components, the problem is that styled components change class every time a change on the input is made, and the class change make the component to re-render.

the solution is to declare the styled component outside the function component like this.

const FormButton = styled.button``

export default function Button(){
   return(   
      <FormButton>Log In</FormButton>        
)
0

I had a similar problem with multiple inputs(re-useable custom components), I just simply added key to the input and it resolved my issue. This will solve your problem even with multiple inputs. (This was happening due to re-renders of parent component because when react re-renders it doesn't know which input had focus because it didn't had the key from those inputs to identify which one had the focus.) please don't never ever add rand() function as a key id(for newbie's)

**e.g Focues error code due to wrong key props **

return(
 <CustomInput key={rand()} placeHolder="email" type="email" data= 
 {onChangeHandler}/>
 <CustomInput key={rand()} placeHolder="password" type="password" 
 data= 
 {onChangeHandler}/>
 <CustomInput key={rand()} placeHolder="name" type="name" data= 
 {onChangeHandler}/>
 <CustomInput key={rand()} placeHolder="age" type="age" data= 
 {onChangeHandler}/>
 )

Explination of above code .The child component (Custom input component had a useState and when ever a user entered in the input the on change handler use to execute on every single key stroke which caused the parent component to re-render and React get confused after re-rendering becasue of the wrong key props(rand() produced new key props which were differend from previous key prop which made react confuse and thus the focus goes out)

Bellow is the correct code

return(
 <CustomInput key="id1" placeHolder="email" type="email" data= 
 {onChangeHandler}/>
 <CustomInput key="id2" placeHolder="password" type="password" 
 data= 
 {onChangeHandler}/>
 <CustomInput key="id3" placeHolder="name" type="name" data= 
 {onChangeHandler}/>
 <CustomInput key="id4" placeHolder="age" type="age" data= 
 {onChangeHandler}/>
 )

Explanation of above code Now after changing the key to a fixed id, React will know to put back focus on the correct input after the re-render of the parent computer because the key prop(e.g "id1") will be same after the re-render

  • Welcome to Stack overflow :) Just letting you know that giving an example or links to examples would have greatly increased the readability of this answer. – Gander7 Aug 12 '23 at 16:29
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 12 '23 at 16:29
  • @Gander7 Please review now. – Abdul Moiz Iqbal Aug 16 '23 at 20:15