Add a `useField` hook to be used in custom components
See original GitHub issueAs of now, when adding custom components to the form, there is no easy way to customize them based on the form state. We have the renderField
prop but that leads to verbose code to keep the layout for different field types intact.
Part of this is adding a context to allow RHF’s useFormContext
to be used (see #37). This doesn’t include the individual field states though (defined in https://github.com/SeasonedSoftware/remix-forms/blob/main/packages/remix-forms/src/createForm.tsx#L47-L62).
A relatively simple solution would be to add something like a FieldContextProvider
around each field, where the props of the Field
type are passed through. This way, custom components (input, but also label etc) could easily implement things like error and required indicators, like such:
const MyInput = (props) => {
const { errors } = useField();
return <input {...props} className={errors ? 'border-red-600' : 'border-gray-200'} />;
}
const MyLabel = ({ children, ...props }) => {
const { required } = useField();
return <label {...props}>{children}{required ? ' *' : ''}</label>;
}
Basically this will allow the customization that the render props have currently, but take it a step further and make it easier to have customizations applied by default.
Issue Analytics
- State:
- Created 9 months ago
- Comments:5 (5 by maintainers)
Top GitHub Comments
1.4.0 released it 🎉
Thank you, @bvangraafeiland, for the great contribution!
Actually ended up not exposing the context provider at all, so there was no need for an intermediate component. The context provider is applied directly on the field component now.