Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my Input Field lose focus after typing a single character in React.js?

In my react.js component, input field is lose focus whenever a character is typed and need to click on the input field again to type or edit the next character. Why's this happening?

Here is my code :

// State to store DataSource
  const [dataSource, setDataSource] = useState<any>(data);

  const handleOnchange = (event: any, props: any) => {
    const newData = [...dataSource];
    const itemIndex = newData.findIndex(
      (item) => item.OrderID === props.OrderID
    );
    newData[itemIndex].Freight = event.target.value;
    setDataSource(newData);
  };

  // Custom Grid Component
  const gridTemplate = (props: any) => {
    const val = props.Freight;
    return (
      <div>
        <input value={val} onChange={(event) => handleOnchange(event, props)} />
      </div>
    );
  };

I've already tried changing onChange to onBlur, but no help!

Thanks

like image 250
Anandhu Remanan Avatar asked Oct 16 '25 01:10

Anandhu Remanan


2 Answers

If the value prop is constantly updated with each keystroke, it causes the input field to lose focus because the component is being re-rendered.

You need to separate the value of the input field from the state and only update the state when necessary.

like image 68
CL22 Avatar answered Oct 18 '25 15:10

CL22


If I understand correctly gridTemplate is a component created inside another component.

The rule is: never ever create component inside another component if it is not necessary to do that. If it is required to do that, use useCallback. Move the inner component gridTemplate outside of your component and pass the things it require as props

On each render it gets new reference and React thinks it is new component and unmounts the previuos one and mounts the new one

like image 28
Oki Avatar answered Oct 18 '25 14:10

Oki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!