Rate
Select or display a rating.
Basic usage
Click the selected rating again to clear it to 0, or set allowClear={false} to prevent clearing. Hover previews a rating; leaving restores the selection.
import { FormField, Rate } from '@ifhover/leaf-ui';
export function RateBasic() {
return (
<FormField label="Project rating" layout="vertical">
<Rate defaultValue={3} />
</FormField>
);
}
Examples
Half-star ratings
Enable allowHalf to select in increments of 0.5. value and onChange use the corresponding decimal values.
import { FormField, Rate } from '@ifhover/leaf-ui';
export function RateHalf() {
return (
<FormField label="Project rating" layout="vertical">
<Rate defaultValue={3.5} allowHalf />
</FormField>
);
}
Read only and disabled
Both prevent changes. Use readOnly when the value must still be included in form submission.
import { Flex, Grid, Rate, Text } from '@ifhover/leaf-ui';
export function RateStates() {
return (
<Grid columns={{ xs: 1, sm: 2 }} gap={16} align="center">
<Text tone="muted">Read only</Text>
<Flex align="center" wrap>
<Rate aria-label="Read-only rating" defaultValue={3} readOnly />
</Flex>
<Text tone="muted">Disabled</Text>
<Flex align="center" wrap>
<Rate aria-label="Disabled rating" defaultValue={3} disabled />
</Flex>
</Grid>
);
}
Controlled rating
Manage the rating with value and onChange. Reset application state when the form resets; controlled fields do not restore themselves.
import { Button, FormField, Rate, Space, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';
export function RateControlled() {
const [value, setValue] = useState(3);
return (
<Space direction="vertical" align="start">
<FormField label="Project rating" layout="vertical">
<Rate value={value} onChange={setValue} />
</FormField>
<Text tone="muted" role="status">
Current rating: {value}
</Text>
<Button variant="outline" onClick={() => setValue(3)}>
Reset
</Button>
</Space>
);
}
Rating colors
colorByValue changes the color with the score. Set color for a fixed color, which takes precedence over score-based colors.
import { Flex, Grid, Rate, Text } from '@ifhover/leaf-ui';
export function RateColors() {
return (
<Grid columns={{ xs: 1, sm: 2 }} gap={16} align="center">
<Text tone="muted">By score</Text>
<Flex align="center" wrap>
<Rate aria-label="Score-based colors" defaultValue={2} colorByValue />
</Flex>
<Text tone="muted">Fixed color</Text>
<Flex align="center" wrap>
<Rate aria-label="Fixed color" defaultValue={2} color="#1d9bf0" />
</Flex>
</Grid>
);
}
Use FormField for a label and name to include the value in FormData. Clearing submits an empty string. Uncontrolled ratings support form reset; set required to require a nonzero rating. See Form for form integration.
Arrow keys adjust the rating, Home / End go to the ends, and Delete / Backspace clear when clearing is allowed.
API
Rate API
Configure the rating value, precision, read-only state and clearing behavior.