Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

losing focus on input field in react form

i am creating simple input field but whenever i type a letter it loses focus , why is it happening ?

   <form onSubmit={(e) => submitPost(e)}>
        <input
          placeholder="Enter First Name"
          type="text"
          onChange={(e) => setFirstName(e.target.value)}
          name="firstname"
          value={firstName}
        />
        <input
          placeholder="Enter Last Name"
          onChange={(e) => setlastName(e.target.value)}
          type="text"
          name="lastname"
          value={lastName}
        />
</form>

if this information is not sufficient then i have file link below too ->
https://codesandbox.io/s/compassionate-gauss-pq2wr?file=/src/App.js:1312-1574
there are some answers on google i can’t quite follow them according to my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s Because you are re creating the Container component on every state change, it will create a new input every time so the focus gets lost

Please try out try out this code sandbox https://codesandbox.io/s/charming-dust-ybh63z?file=/src/App.js

When the props are changed, you are creating a new Container component, so whenever a new Container get’s created all the children will be re created not re rendered so the focus will is being lost on every state change

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading