react-hook -form with SliderComponent input

Viewed 1633

Im new to react and I am trying to use a SliderComponent in a react Hook form but I cant seem able to fully understand how Controller works.

Here is my SliderComponent using react-input-slider:

export default function SliderComponent(props) {
    
  const { axis, xmax, xmin, xstep, onChange } = props;;

  return (
    <div>
      <Slider
        axis={axis}
        x={value.x}
        xmax={xmax}
        xmin={xmin}
        xstep={xstep}
        onChange={onChange}
      />
    </div>
  );
}

And here is my form:

export default function BiometricForm() {
      const { handleSubmit, control } = useForm();
    
  return (
    <div className="registerForm_Container">
      <form onSubmit={handleSubmit(onsubmit)}>
        <Controller
          control={control}
          name="test"
          render={({ props: { x, axis, xmax, xmin, xstep } }) => (
            <SliderComponent
              axis={"x"}
              xmax={100}
              xmin={1}
              xstep={1}
              value={x}
              onChange={(e) => x.onChange(parseInt(e.target.value))}
            />
          )}
        />
        <button className="registerForm_Container_button" type="submit">
          Register
        </button>
      </form>
    </div>
  );
}

I think it might be something to do with useState and that I am not able to reach useState of component. I have read that maybe its not necessary , any help? Thank you!

1 Answers

You are absolutely right, if you use RHF you don't need useState because RHF handles the form state for you. The important thing here is to pass an onChange handler to your <SliderComponent />, so that RHF can watch for value changes of your <SliderComponent /> and update the form state. You should also provide a defaultValue for the field, if you don't want it to be undefined if the user doesn't change the slider before submitting.

Also without the useState inside <SliderComponent />, you can also omit the <SliderComponent /> and just use <Slider />.

function BiometricForm() {
  const { handleSubmit, control } = useForm();

  const onSubmit = (data) => console.log(data);

  return (
    <div className="registerForm_Container">
      <form onSubmit={handleSubmit(onSubmit)}>
        <Controller
          control={control}
          name="test"
          defaultValue={50}
          render={({ field: { value, onChange } }) => (
            <Slider
              axis={"x"}
              xmax={100}
              xmin={1}
              xstep={1}
              onChange={({ x }) => onChange(x)}
              x={value}
            />
          )}
        />
        <input type="submit" />
      </form>
    </div>
  );
}

Edit React Hook Form - Slider Controller (forked)

Related