Skip to content

Commit

Permalink
add example for controlled components (#6519)
Browse files Browse the repository at this point in the history
* add example for controlled components

the alternative for custom input fields when useRegister can't be used.

* readability change

Co-authored-by: Dominic Saadi <dominiceliassaadi@gmail.com>

* change props import

only import type to make clear that all you need is the type

Co-authored-by: Dominic Saadi <dominiceliassaadi@gmail.com>

* remove last line

Co-authored-by: Dominic Saadi <dominiceliassaadi@gmail.com>

* pluralize props

* add a title

* change hyperlink

* Update docs/docs/forms.md

Co-authored-by: Dominic Saadi <dominiceliassaadi@gmail.com>
  • Loading branch information
m-raschle and jtoar authored Oct 7, 2022
1 parent 1614d10 commit b7cfa46
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions docs/docs/forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,65 @@ const RequiredField = ({ label, name, validation }) => {
}
```

### Controlled Component Fields

If you're working with a fully-featured component library, or have your own production-ready components, you may want to integrate them with Redwood's forms seamlessly.
You can via Redwood forms' `useErrorStyles` hook and React Hook Form's `Controller` component.
The following example shows how you could go about integrating a component from [`primereact`](https://www.primefaces.org/primereact/) for use in in Redwood's forms like any of the named-input fields listed above:

```tsx title="web/src/components/ToggleButtonField/ToggleButtonField.tsx"
import { ToggleButton } from 'primereact/togglebutton'
import type { ToggleButtonProps } from 'primereact/togglebutton'

import { Controller, RegisterOptions, useErrorStyles } from '@redwoodjs/forms'

interface Props extends ToggleButtonProps {
validation?: RegisterOptions
errorClassName?: string
}

const ToggleButtonField = (props: Props) => {
const {
name,
className,
errorClassName,
defaultValue,
validation,
style,
...propsRest
} = props

const { className: componentClassName, style: componentStyle } =
useErrorStyles({
className: className,
errorClassName: errorClassName,
name: name,
})

return (
<Controller
name={name}
defaultValue={defaultValue}
rules={validation}
render={({ field: { onChange, onBlur, value, name, ref } }) => (
<ToggleButton
{...propsRest}
checked={value}
onChange={onChange}
onBlur={onBlur}
ref={ref}
name={name}
className={componentClassName}
style={{ ...componentStyle, ...style }}
/>
)}
/>
)
}

export default ToggleButtonField
```

## `<SelectField>`

Renders an HTML `<select>` tag.
Expand Down

0 comments on commit b7cfa46

Please sign in to comment.