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

React: Input Field Loses Focus When Typing

How do I prevent my input field from losing focus when typing?

Every time I type in one of my input fields, the field loses focus. Researching the issue, I came across this post which talks about how the issue is one component is inside another component.

The reason I’m nesting components is because I’m creating input fields through mapping. I’d like the user to be able to input a value and then have another value computed on that same row. If I don’t nest the value, then the same state value is used on all the mapped inputs which causes the same value to be typed into every input on the page.

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

I’m trying to have an individual input field state for each value. However, doing so now causes the issue where typing into a input field causes that field to lose focus.

ProjectiveAnalytics.js:

export default function ProjectiveAnalytics({
  predictiveData,
  completionPercentage,
}) {
  return (
    <>
      {predictiveData &&
        predictiveData.map((response) => {
          return (
            <>
              <div key={uuidv4()}>
                <ProjectiveAnalyticsRow
                  response={response}
                  completionPercentage={completionPercentage}
                />
              </div>
            </>
          );
        })}
    </>
  );
}

ProjectiveAnalyticsRow.js:

export default function ProjectiveAnalyticsRow({
  response,
  completionPercentage,
}) {
  const [updateAdSpend, setUpdateAdSpend] = useState("");

  const handleChange = (event) => {
    setUpdateAdSpend(event);
  };

  return (
    <>
      <div className={analyticStyles.resultsColumnDescription} key={uuidv4()}>
        <div>{response.response}</div>
        <div>
          <input
            type="text"
            placeholder="Input Ad Spend"
            value={updateAdSpend}
            onChange={(e) => handleChange(e.target.value)}
          />
        </div>
        <div>${(response.sum / (completionPercentage / 100)).toFixed(2)}</div>
      </div>
    </>
  );
}

>Solution :

The root cause is the key on the divs. You can initialise it in a didMount useEffect or something. That way it won’t change on each render.

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