Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add example for controlled components #6519

Merged
merged 10 commits into from
Oct 7, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions docs/docs/forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,67 @@ const RequiredField = ({ label, name, validation }) => {
}
```

### Controlled Component Fields

If you're working with a fully-loaded component library, or bring your own production-ready components you may want them to integrate with Redwood seemlessly.

You can create these custom fields through the use of Redwood's `useErrorStyles` and React Hook Form's `Controller`.

The following example shows a component from [`primereact`](https://www.primefaces.org/primereact/) which can be used in Forms like any of the named input fields (listed above).
m-raschle marked this conversation as resolved.
Show resolved Hide resolved

```jsx
m-raschle marked this conversation as resolved.
Show resolved Hide resolved
import { ToggleButton, ToggleButtonProps } from 'primereact/togglebutton'
m-raschle marked this conversation as resolved.
Show resolved Hide resolved

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

interface Prop extends ToggleButtonProps {
m-raschle marked this conversation as resolved.
Show resolved Hide resolved
validation?: RegisterOptions
errorClassName?: string
}

const ToggleButtonField = (prop: Prop) => {
m-raschle marked this conversation as resolved.
Show resolved Hide resolved
const {
name,
className,
errorClassName,
defaultValue,
validation,
style,
...propRest
} = prop
m-raschle marked this conversation as resolved.
Show resolved Hide resolved

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
{...propRest}
m-raschle marked this conversation as resolved.
Show resolved Hide resolved
checked={value}
onChange={onChange}
onBlur={onBlur}
ref={ref}
name={name}
className={componentClassName}
style={{ ...componentStyle, ...style }}
/>
)}
/>
)
}

export default ToggleButtonField

m-raschle marked this conversation as resolved.
Show resolved Hide resolved
```

## `<SelectField>`

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