Home > Blockchain >  Input Type loses focus while typing while working with useState
Input Type loses focus while typing while working with useState

Time:12-07

The input losses its focus when i start typing a character. I saw many stackoverflow answers but none is working hep me out. I haved added unique keys also. What is the reason the code is not working. Without the state it is working fine. But after adding the state. The input losses the focus

import React, { useState } from "react";

const Footer = ({ formData }) => {
  const [colorsArray, setColors] = useState(["Red", "Green", "Blue", "Yellow"]);
  const [sizeArray, setSizes] = useState(["S", "M", "L", "XL"]);

  const [sizeInput, setsizeInput] = useState("");

  const colorElementRemoveHandler = (indexToRemove) => {
    const filteredValue = colorsArray.filter((data, index) => {
      return indexToRemove !== index;
    });
    setColors(filteredValue);
  };

  const sizeElementRemoveHandler = (indexToRemove) => {
    const filteredValue = sizeArray.filter((data, index) => {
      return indexToRemove !== index;
    });

    setSizes(filteredValue);
  };

  const addColorHandler = (e) => {
    let input = e.target.value.toLowerCase();
    if (input.length > 2) {
      let temp = colorsArray;
      temp.push(input);
      setColors(temp);
    }
  };
  const addSizeHandler = (e) => {
    let input = e.target.value.toUpperCase();
    if (input.length > 0) {
      let temp = sizeArray;
      temp.push(input);
      setSizes(temp);
      console.log(sizeArray);
    }
  };

  const Test = () => {
    return (
      <input
        type="text"
        onChange={(e) => {
          setsizeInput(e.target.value);
        }}
        value={sizeInput}
      />
    );
  };

  const VariantUI = () => {
    return (
          <div>
            <label>Size</label>
            <input
              id="optionName"
              type="text"
              placeholder="e.g S, M, L, XL"
              onChange={(e) => {
                setsizeInput(e.target.value);
              }}
              value={sizeInput}
            />
          </div>
              <ul>
                {sizeArray.map((data, index) => {
                  return (
                    <li key={index}>
                      {data}
                      <i onClick={() => {sizeElementRemoveHandler(index);}}></i>
                    </li>
                  );
                })}
              </ul
    );
    };

  return (     
        <VariantUI formData={formData} />
   
   );
   };

   export default Footer;


`

Thanks in advance

CodePudding user response:

const Footer = ({ formData }) => {
  // ..
  const VariantUI = () => {
  // ...
  return (<VariantUI formData={formData} />)
}

You are creating a brand new type of component (VariantUI), in the middle of rendering Footer. This will happen on ever render. Each VariantUi function might have the same text as the previous one, but it's a different function, and thus to react it's a different type of component. Since it's a different type of component, the old one unmounts, and the new one mounts. A newly-mounted <input> does not have focus.

Component types must be defined only once, not on ever render. So VariantUI needs to be moved outside of footer. Since you're currently relying on closure variables, you will need to changes those to props:

const VariantUI = ({
  sizeArray, setSizes, sizeInput, setSizeInput,  // I might have missed a couple props
}) => {
 // ...
}

const Footer = ({ formData }) => {
  // ...
  return (
    <VariantUI
      sizeArray={sizeArray}
      setSizes={setSizes}
      sizeInput={sizeInput}
      setSizeInput={setSizeInput}
    />
  );
}
  • Related