Skip to Content
Piplup
@piplup/rhf-adaptersmui-materialComponents

MuiRatingElement

Use MUI Rating with react-hook-form without writing a Controller. MuiRatingElement binds the star value and validation to a form field.

Import

import { MuiRatingElement } from '@piplup/rhf-adapters/mui-material';

Usage

'use client';import Stack from '@mui/material/Stack';import { MuiButtonElement, MuiRatingElement } from '@piplup/rhf-adapters/mui-material';import { useForm } from 'react-hook-form';export default function Page() {  const { control, handleSubmit } = useForm({    defaultValues: { rating: 3 },  });  return (    <form onSubmit={handleSubmit((values) => alert(JSON.stringify(values, null, 2)))}>      <Stack direction="column" spacing={2}>        <MuiRatingElement control={control} name="rating" />        <div>          <MuiButtonElement control={control} type="submit" variant="contained">            Submit          </MuiButtonElement>        </div>      </Stack>    </form>  );}

Props

Prop

Type

MuiRatingElement supports props of the MUI Rating component, along with additional adapter-specific props. For a complete list of available Rating properties, refer to the MUI API documentation.

The ref is forwarded to the underlying <Rating /> component.

useMuiRatingAdapter

useMuiRatingAdapter connects an MUI Rating to a React Hook Form field and returns props you spread onto it. It's what MuiRatingElement uses internally.

Use the element when stars alone are enough. Reach for the hook when the rating needs things the element doesn't render: a legend, a word label for the hovered star, or an error message under the stars.

Import

import { useMuiRatingAdapter } from '@piplup/rhf-adapters/mui-material';

A required rating with a label that follows the hovered star. Click the selected star again to clear it, then submit to see the error.

How was your stay?
'use client';import * as React from 'react';import Box from '@mui/material/Box';import FormHelperText from '@mui/material/FormHelperText';import Rating from '@mui/material/Rating';import Stack from '@mui/material/Stack';import Typography from '@mui/material/Typography';import { MuiButtonElement, useMuiRatingAdapter } from '@piplup/rhf-adapters/mui-material';import { useForm } from 'react-hook-form';import type { Control } from 'react-hook-form';type FormValues = { score: null | number };const LABELS: Record<number, string> = {  1: 'Poor',  2: 'Fair',  3: 'Good',  4: 'Very good',  5: 'Excellent',};// A required rating with a word next to the stars. Click the selected star// again to clear it; the field becomes `null` and the required rule fails.function ScoreField({ control }: { control: Control<FormValues> }) {  const [hover, setHover] = React.useState(-1);  const { error, helperText, ...adapter } = useMuiRatingAdapter<    null | number,    FormValues,    'score',    HTMLSpanElement  >({    composeHelperText: true,    control,    messages: { required: 'Please rate your stay' },    name: 'score',    required: true,  });  const shown = hover !== -1 ? hover : adapter.value;  return (    <Stack spacing={0.5}>      <Typography component="legend">How was your stay?</Typography>      <Stack direction="row" spacing={2} sx={{ alignItems: 'center' }}>        <Rating {...adapter} onChangeActive={(_event, value) => setHover(value)} />        <Box sx={{ minWidth: 80 }}>{shown ? LABELS[shown] : null}</Box>      </Stack>      {helperText ? <FormHelperText error={error}>{helperText}</FormHelperText> : null}    </Stack>  );}export default function Page() {  const { control, handleSubmit } = useForm<FormValues>({    defaultValues: { score: null },  });  return (    <form onSubmit={handleSubmit((values) => alert(JSON.stringify(values, null, 2)))} noValidate>      <Stack direction="column" spacing={2}>        <ScoreField control={control} />        <div>          <MuiButtonElement control={control} type="submit" variant="contained">            Send review          </MuiButtonElement>        </div>      </Stack>    </form>  );}

How it works

Empty value is null. An undefined field value reaches Rating as null, so it stays controlled and shows no stars. On change, the hook stores the number Rating reports. When the user clicks the selected star again, Rating reports null and that's what gets stored. required rejects null.

max and min. max is returned and sets the number of stars, as on Rating. Both max and min also become validation rules:

PropRuleDefault message
minRating must be at least minValue must be min or later.
maxRating must be at most maxValue must be max or earlier.

The max rule can't fail, since Rating doesn't go past max. The min rule is useful for "at least 2 stars", but the default wording is generic, so set messages.min. A min of 0 adds no rule, and an empty (null) rating passes the min rule, so add required if a rating must be given. min isn't a Rating prop; it only affects validation.

Errors. Rating doesn't show errors. The hook returns error and helperText; render them in a FormHelperText. With composeHelperText: true, helperText is the field's error message, falling back to your helperText when there's no error.

Blur. The returned onBlur marks the field as touched when focus leaves the rating's radio inputs.

Rating has no error or helperText props. Remove them from the returned object before spreading, as the demo and the element do.

Props

Prop

Type

Return value

Prop

Type

See also

On this page