Home > Software engineering >  React-Hook-Form register function without prop spreading
React-Hook-Form register function without prop spreading

Time:10-10

I am using React Hook Form to register data form an input like so:

<input
          className="block w-full box-border rounded-lg mb-5 text-sm p-[1em] border-[1px] border-gray-400 h-[46.8px]"
          id="passwordInput"
          {...register('password', { required: true })}
          type="password"
        />

Its working great and fine until the moment I implement eslint with airbnb rules into my project. Eslint pushes the idea that prop spreading should not be used because we might use props that are not even neccesary.

Prop spreading is forbiddeneslintreact/jsx-props-no-spreading

Is there a way to not use an ignore func to ignore the message from eslint and use the register function from react hook form without spreading?

CodePudding user response:

according to documentation, you can use this:

const { onChange, onBlur, name, ref } = register('firstName'); 
// include type check against field path with the name you have supplied.
        
<input 
  onChange={onChange} // assign onChange event 
  onBlur={onBlur} // assign onBlur event
  name={name} // assign name prop
  ref={ref} // assign ref prop
/>
// same as above
<input {...register('firstName')} />

https://react-hook-form.com/api/useform/register/


edit: more inputs

const firstNameReg = register('firstName');
const lastNameReg = register('lastName'); 
        
return <><input 
  onChange={firstNameReg.onChange} 
  onBlur={firstNameReg.onBlur} 
  name={firstNameReg.name} 
  ref={firstNameReg.ref} 
/>
<input 
  onChange={lastNameReg.onChange} 
  onBlur={lastNameReg.onBlur} 
  name={lastNameReg.name} 
  ref={lastNameReg.ref} 
/><>;
  • Related