DEV Community

Abhijit Sawant
Abhijit Sawant

Posted on

onChange does not trigger when typing but triggers after clicking outside the textfield.

I have 3 react components . Lets say, A B & C. C is a textfield component. C is present in B . B is just a parent component for C. Component B is present/imported in A. We are using react-hook-form version 7.

My issue is whenever I type anything inside the textfield, the onChange method does not trigger. But when I click anywhere outside the textfield, the onChange method of textfield triggers.

Also, the textfield component C is wrapped in a Controller tag of react-hook-form.

In my Comp A, I have a function convertToText to carry out required calculation, for which I need the value entered inside the textfield in component C. handleChange is a event by which I keep a watch on the onChange attribute of CompC (textfield).

For this, I pass the props from Component A to Component C via Componet B as follows:

const CompA = () => {
/other lines of code/
return(

)
}

const CompB = (props) =>{
/other lines of code/

const {control, getValues, setValue, handleChange, ...} = useFormField(props.label, validations, input, props )

const renderInput = (value, onChange, onBlur, ref) => {
onChange={ (e)=> handleChange(e,onChange,name)}
value={value}
/>
}

return(
control={control}
render=({field: {value, onChange, onBlur, ref}}) = > renderInput(value, onChange, onBlur, ref)
/>
)

}

/* useFormField is a react hook function*/

// useFormField.js

function useFormField(label, validations, input , props)
{
const {control, getValues, setValue, formState:{errors}, trigger } = useFormContext();

const handleChange = (e, onChange, name) => {
if(input && input.type === 'number')
{

onChange(Number(e.target.value))
}
else if(typeof e.value === 'number')
{
onChange(e.value)
}
else if(onChange) onChange(e);

if(props.handleChange)
{
props.handleChange({
event:e,
value: e.value? e.value: e.target.value,
name,
setValue,
getValues,
addToast
});
}
};
return { control, getValues, setValue, handleChange, trigger};

}
}

export default useFormField;

please help me with this.

Top comments (1)

Collapse
 
zoppatorsk profile image
Zoppatorsk

First, i don't know much react, but it that should not matter. Second, u can format your code by doing 3 backticks and lang after, in this case js and then end with 3 backticks
like this

function useFormField(label, validations, input , props)
{
Enter fullscreen mode Exit fullscreen mode

see.. looks nice

And yes, onchange does only run when the field lose focus.
Try using oninput instead, should work better.
see this link for more information