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
3
Answers
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 propsOn each render it gets new reference and React thinks it is new component and unmounts the previuos one and mounts the new one
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.
By looking at the Stackblitz you shared it seems like you’re not integrating Syncfusion right, they don’t allow you to have controlled inputs in their templates because of their internal rendering logic.
Instead you should setup an event listener using a reference to the grid to listen to changes (
keyup
) on grid elements and retrieve the changes (input value). Since the input will be uncontrolled (you’re only passing adefaultValue
and you don’t control what its current value will be) you won’t have to update its value since it will be updated already (last thing the user typed).I adapted the following code from their docs on edition to give you an idea on how to set it up: