Home > Net >  I have rendered two components and whenever I type something input field input field loses its focus
I have rendered two components and whenever I type something input field input field loses its focus

Time:02-13

Here is my component into which component is rendered

const BasicInfo=({
product,
  handleChange,
  handleTags,
  productData,
  deleteTags,
  categories,
  customProduct,
  handleCustomChange,
  setCustomProduct,
})=>{
function increasenumber() {
    var hello = numberoffields;
    hello = hello   1;
    setNumberoffields(hello);
    setCustomProduct((arr) => [...arr, { typeoffield: "", label: "" }]);
  }
const DisplayCustomInput = () => {
    if (product.customCategory.includes(product.category)) {
      return (
        <div>
          <div>
            <button onClick={increasenumber}>Add input field</button>
          </div>
          <DisplayInputs
            numberoffields={numberoffields}
            customProduct={customProduct}
            handleCustomChange={handleCustomChange}
          />
        </div>
      );
    } else {
      return null;
    }
  };

  return (
<DisplayCustomInput />
)
}

My DisplayInputs looks like

export default function DisplayInputs({
  numberoffields,
  customProduct,
  handleCustomChange,
}) {
const rows = [];
  for (let index = 0; index < numberoffields; index  ) {
    console.log(index);
    rows.push(
<div key={index}>
        <label htmlFor="label">
          Enter label for input field for accepting data
        </label>

        <input
          value={customProduct[index] ? customProduct[index].label : ""}
          onChange={handleCustomChange(index, "label")}
          id="label"
        />
</div>
)
}
return rows 
}

Whenever a character if fed to the input field it loses focus and if I use DisplayCustomInput as jsx instead of component then on increasing numberoffields the whole page gets reload.

CodePudding user response:

You can use a ref in React. You initial her in the child and you call something like nomRef.current.focus on useEffect in the parent, useEffect with dependency the value that the input change.

One thing more :

onChange={() => handleCustomChange(index, "label")}

and not onChange={handleCustomChange(index, "label")} (because without () => you execute the function on mount.

If you need about ref : https://fr.reactjs.org/docs/refs-and-the-dom.html

Say me if it's good for you

  • Related