Created
October 16, 2024 21:56
-
-
Save AlanGreyjoy/6bbf2f02e6b8a11e88333b375b4fa6f0 to your computer and use it in GitHub Desktop.
RHF Error Card
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { Alert, Box, Typography } from '@mui/joy' | |
import Icon from 'src/_core/components/icon' | |
/** | |
* FormAlerts component | |
* @param {Object} props | |
* @param {Object} props.errors - Error object | |
* @param {string} [props.variant='soft'] - Alert variant | |
* @param {string} [props.color='danger'] - Alert color | |
* @param {boolean} [props.sticky=false] - Whether the alert should be sticky | |
*/ | |
const FormAlerts = ({ errors = {}, variant = 'soft', color = 'danger', sticky = false }) => { | |
const getErrors = React.useMemo(() => { | |
return Object.entries(errors).flatMap(([key, value]) => { | |
if (Array.isArray(value)) { | |
return value.flatMap((subValue, subKey) => | |
Object.entries(subValue) | |
.map( | |
([subSubKey, { message }]) => | |
message && ( | |
<Typography | |
key={`${key}-${subKey}-${subSubKey}`} | |
level='body-sm' | |
sx={{ fontWeight: 600 }} | |
> | |
* {message} | |
</Typography> | |
) | |
) | |
.filter(Boolean) | |
) | |
} | |
return ( | |
<Typography | |
key={key} | |
level='body-sm' | |
sx={{ fontWeight: 600 }} | |
> | |
* {value.message} | |
</Typography> | |
) | |
}) | |
}, [errors]) | |
if (Object.keys(errors).length === 0) return null | |
return ( | |
<Alert | |
variant={variant} | |
color={color} | |
sx={{ | |
alignItems: 'flex-start', | |
mt: 1, | |
...(sticky && { position: 'sticky', top: 10 }) | |
}} | |
startDecorator={<Icon icon='fluent:alert-24-filled' />} | |
> | |
<Box | |
display='flex' | |
flexDirection='column' | |
alignItems='flex-start' | |
> | |
<Typography level='body-md'>Please correct the following errors:</Typography> | |
<Box>{getErrors}</Box> | |
</Box> | |
</Alert> | |
) | |
} | |
export default FormAlerts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment