why is first letter dead in react-hook-form input

Viewed 2071

i need help to understand why the first letter in the simple input component is not registered.

I've created a simple controlled input from the examples but its not working properly.

i created an example for you https://stackblitz.com/edit/react-9zezqx

const App = () => {

const { register, handleSubmit, watch, errors, reset, control, formState } = useForm({ mode: 'onChange' });

console.log(errors)
    return (
      <div>
        <form onSubmit={handleSubmit(() => console.log("submit"))}>
            <Controller
                as={TextInput}
                name="firstname"
                defaultValue=""
                control={control}
                inputRef={register({ required: true, minLength: 8 })}
                hasErrors={errors.firstname !== undefined}
            />
            <br/>
            <Controller
                as={TextInput}
                name="hobby"
                defaultValue=""
                control={control}
                inputRef={register({ required: true, minLength: 8 })}
                hasErrors={errors.hobby !== undefined}
            />
            </form>
      </div>
    );

}

render(<App />, document.getElementById('root'));



import * as React from 'react';

export const TextInput = (props) => {
  return(
    <>
    <input    
      type="text"
      name={props.name}
      value={props.value}
      onChange={props.onChange}
      ref={props.inputRef}
     />
     {props.hasErrors && (<h2>errors!!</h2>)}
     </>
  )
}
4 Answers

okay i found the bug causing it in 'onBlur' aswell

reValidateMode: 'onBlur'

Swap the mode to onBlur, this will improve the performance, will trigger only when the user leaves the field, which is suppose to happen, and also does not swallow the first input.

onChange skips the first letter, because the default value will be used for the initial onChange call, which is empty.

You are probably using an uncontrolled input. If that's the case use defaultValue instead of value.

Reference

Related