Home > front end >  React: Input Field Loses Focus When Typing
React: Input Field Loses Focus When Typing

Time:02-17

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.

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>
    </>
  );
}

CodePudding user response:

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.

  • Related