In React ES6, why does the input field lose focus after typing a character?

it is because you are rendering the form in a function inside render().

Every time your state/prop change, the function returns a new form. it caused you to lose focus.

Try putting what's inside the function into your render directly.

<main id="main" role="main">
    <div className="container-fluid">
        <FormPostSingle />
    </div>
</main>

===>

<main id="main" role="main">
    <div className="container-fluid">
        <form onSubmit={onSubmit}>
            <InputText name="title" label="Title" placeholder="Enter a title" onChange={onChange} value={valueTitle} />
            <InputSubmit name="Save" />
        </form>
    </div>
</main>

This happened to me although I had keys set!

Here's why:

I was using a key from a text field. Inside the same block; I had an input field to update the value of the same text field. Now, since component keys are changing, react re-renders the UI. Hence loosing focus.

What to take from this:

Don't use keys which are constantly changing.


What's happening is this:

When your onChange event fires, the callback calls setState with the new title value, which gets passed to your text field as a prop. At that point, React renders a new component, which is why you lose focus.

My first suggestion would be to provide your components keys, particularly the form and the input itself. Keys allow React to retain the identity of components through renders.

Edit:

See this documentation on keys: https://reactjs.org/docs/lists-and-keys.html#keys


Had the same issue and solved it in a quick & easy manner: just calling the component with {compName()} instead of <compName />

For instance, if we had:

const foo = ({param1}) => {
   // do your stuff
   return (
      <input type='text' onChange={onChange} value={value} />
   );
};

const main = () => (
   <foo param1={true} />
);

Then, we just need to change the way we call the foo() component:

const main = () => (
   {foo({param1: true})}
);