Home > front end >  losing focus on input field in react form
losing focus on input field in react form

Time:03-01

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

CodePudding user response:

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

  • Related