2
votes

I am trying to use Material UI's React rating component within a react-hook-form.

  ... 
  <form onSubmit={handleSubmit(onSubmit)}>
      <FormControlLabel
        control={
          <Checkbox
            inputRef={register}
            name="remember"
            defaultValue={false}
          />
        }
        label="remember"
      />
      <br />
      <FormControlLabel
        control={
          <Rating
            inputRef={register}
            name="rating"
            defaultValue={2}
            precision={1}
            icon={<RadioButtonUncheckedIcon fontSize="inherit" />}
          />
        }
        label="select rating"
      />
      <Button type="submit">
        Submit
      </Button>
    </form>
    ...

I can't understand why the value from the rating component is not being registered but the checkbox's value is. Please find the code at https://codesandbox.io/s/suspicious-drake-1d0kx?file=/src/form.js (on submit, the rating's value is not printed to the console while the checkbox's value is).

1

1 Answers

3
votes

According to the doc, Rating have no input element to pass ref to like TextField or Checkbox, so a solution is to create an hidden input in replacement to store the rating value

<FormControlLabel
  control={
    <>
      <input
        name="rating"
        type="number"
        value={rating}
        ref={register}
        hidden
        readOnly
      />
      <Rating
        name="rating"
        value={rating}
        precision={1}
        onChange={(_, value) => {
          setRating(value);
        }}
        icon={<RadioButtonUncheckedIcon fontSize="inherit" />}
      />
    </>
  }
  label="select rating"
/>

Below is the forked codesandbox link for the modification

Edit cool-cache-o4o7c