Skip to content

Commit 8e5d56d

Browse files
authored
docs: updating lexical richtext fields (#15968)
Fixes #12835 - explains why setValue alone doesn't update the editor UI - Adds code snippet - adds a warning banner to make the gotcha visually prominent
1 parent 747be91 commit 8e5d56d

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

docs/admin/react-hooks.mdx

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,49 @@ type FieldType<T> = {
7676
}
7777
```
7878
79+
### Updating Lexical Rich Text Fields
80+
81+
The Lexical editor uses `initialValue` — not `value` — as the trigger to re-mount and visually update its content. This is intentional: it prevents unnecessary re-renders on every keystroke. However, it means that calling `setValue` alone will update the form's `value` (and save correctly to the database), but **the editor UI will not reflect the change** until the page is refreshed.
82+
83+
To programmatically update a Lexical rich text field and have the editor visually reflect the new content, you must update both `value` and `initialValue` simultaneously. The way to do this is via `dispatchFields` with an `UPDATE` action, which can set any property of a field's form state at once:
84+
85+
```tsx
86+
'use client'
87+
import { useAllFormFields } from '@payloadcms/ui'
88+
89+
export const MyComponent: React.FC = () => {
90+
const [, dispatchFields] = useAllFormFields()
91+
92+
const updateRichTextField = (newValue) => {
93+
dispatchFields({
94+
type: 'UPDATE',
95+
path: 'myRichTextField', // the field's path in the form
96+
value: newValue,
97+
initialValue: newValue, // required to trigger Lexical re-render
98+
})
99+
}
100+
101+
return (
102+
<button
103+
onClick={() =>
104+
updateRichTextField({
105+
/* new editor state */
106+
})
107+
}
108+
>
109+
Update
110+
</button>
111+
)
112+
}
113+
```
114+
115+
<Banner type="warning">
116+
Using `setValue` from `useField` on a Lexical rich text field will update the
117+
form data (and persist correctly on save), but the editor UI will not visually
118+
update. Use `dispatchFields` with both `value` and `initialValue` set to the
119+
new content to trigger a re-render of the editor.
120+
</Banner>
121+
79122
## useFormFields
80123

81124
There are times when a custom field component needs to have access to data from other fields, and you have a few options to do so. The `useFormFields` hook is a powerful and highly performant way to retrieve a form's field state, as well as to retrieve the `dispatchFields` method, which can be helpful for setting other fields form states.

0 commit comments

Comments
 (0)