@base-ui-components/react
Version:
Base UI is a library of headless ('unstyled') React components and low-level hooks. You gain complete control over your app's CSS and accessibility features.
112 lines (109 loc) • 4.02 kB
JavaScript
'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { useComponentRenderer } from '../utils/useComponentRenderer.js';
import { mergeReactProps } from '../utils/mergeReactProps.js';
import { FormContext } from './FormContext.js';
import { useEventCallback } from '../utils/useEventCallback.js';
/**
* A native form element with consolidated error handling.
* Renders a `<form>` element.
*
* Documentation: [Base UI Form](https://base-ui.com/react/components/form)
*/
import { jsx as _jsx } from "react/jsx-runtime";
const Form = /*#__PURE__*/React.forwardRef(function Form(props, forwardedRef) {
const {
render,
className,
errors,
onClearErrors: onClearErrorsProp,
onSubmit: onSubmitProp,
...otherProps
} = props;
const formRef = React.useRef({
fields: new Map()
});
const onSubmit = useEventCallback(onSubmitProp || (() => {}));
const onClearErrors = useEventCallback(onClearErrorsProp || (() => {}));
const getFormProps = React.useCallback((externalProps = {}) => mergeReactProps(externalProps, {
noValidate: true,
onSubmit(event) {
let values = Array.from(formRef.current.fields.values());
// Async validation isn't supported to stop the submit event.
values.forEach(field => {
field.validate();
});
values = Array.from(formRef.current.fields.values());
const invalidFields = values.filter(field => !field.validityData.state.valid);
if (invalidFields.length) {
event.preventDefault();
invalidFields[0]?.controlRef.current?.focus();
} else {
onSubmit(event);
}
}
}), [onSubmit]);
React.useEffect(() => {
const invalidFields = Array.from(formRef.current.fields.values()).filter(field => field.validityData.state.valid === false);
if (invalidFields.length) {
invalidFields[0]?.controlRef.current?.focus();
}
}, [errors]);
const state = React.useMemo(() => ({}), []);
const {
renderElement
} = useComponentRenderer({
propGetter: getFormProps,
render: render ?? 'form',
ref: forwardedRef,
state,
className,
extraProps: otherProps
});
const contextValue = React.useMemo(() => ({
formRef,
errors: errors ?? {},
onClearErrors
}), [formRef, errors, onClearErrors]);
return /*#__PURE__*/_jsx(FormContext.Provider, {
value: contextValue,
children: renderElement()
});
});
process.env.NODE_ENV !== "production" ? Form.propTypes /* remove-proptypes */ = {
// ┌────────────────────────────── Warning ──────────────────────────────┐
// │ These PropTypes are generated from the TypeScript type definitions. │
// │ To update them, edit the TypeScript types and run `pnpm proptypes`. │
// └─────────────────────────────────────────────────────────────────────┘
/**
* @ignore
*/
children: PropTypes.node,
/**
* CSS class applied to the element, or a function that
* returns a class based on the component’s state.
*/
className: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
/**
* An object where the keys correspond to the `name` attribute of the form fields,
* and the values correspond to the erorr(s) related to that field.
*/
errors: PropTypes.object,
/**
* Event handler called when the `errors` object is cleared.
*/
onClearErrors: PropTypes.func,
/**
* @ignore
*/
onSubmit: PropTypes.func,
/**
* Allows you to replace the component’s HTML element
* with a different tag, or compose it with another component.
*
* Accepts a `ReactElement` or a function that returns the element to render.
*/
render: PropTypes.oneOfType([PropTypes.element, PropTypes.func])
} : void 0;
export { Form };