Retrieving data from rich text editor in spfx web part properties
-
08-02-2021 - |
Question
I am currently creating a custom web part, the webpart is using PropertyFieldCollectionData to collect user data (https://sharepoint.github.io/sp-dev-fx-property-controls/controls/PropertyFieldCollectionData/). I want the user to be able to use a rich text editor so I am using the customFieldId within PropertyFieldCollectionData to render my own controls. I am using it to render the CKeditor and have also tried JoditEditor.
{
id: "customFieldId",
title: "Custom Field",
type: CustomCollectionFieldType.custom,
onCustomRender: (field, value, item, itemId, onUpdate) => {
return (
React.createElement(Editor)
)
}
}
it renders the editor But I am not able to access any of the values that the user has entered in my webpart. How can I get the values entered?
Solution 2
Thought I would come back and share what my code looks like after finally getting this to work. Just in case it can help any one!
{
id: "description",
title: strings.descriptionField,
type: CustomCollectionFieldType.custom,
onCustomRender: (field, value, onUpdate, item, itemId, onError) => {
return (
React.createElement("div", null,
React.createElement(CKEditor, {
data: value,
editor: ClassicEditor,
key: itemId,
value: value,
config: editorConfig,
onInit: (editor: any) => {
editor.plugins.get("FileRepository").createUploadAdapter = (loader: any) => {
return new UploadAdapter(loader);
};
},
onChange: (event: Event, editor: ClassicEditor) => {
const data = editor.getData();
onUpdate(field.id, data);
}
}
)
)
);
}
}
OTHER TIPS
In your code example, the value would have to be passed to the onUpdate
function on your onCustomRender
property.
You can see how this is done in the bottom example on the page you linked:
01. {
02. id: "customFieldId",
03. title: "Custom Field",
04. type: CustomCollectionFieldType.custom,
05. onCustomRender: (field, value, onUpdate, item, itemId, onError) => {
06. return (
07. React.createElement("div", null,
08. React.createElement("input", { key: itemId, value: value, onChange: (event: React.FormEvent<HTMLInputElement>) => {
09. if (event.currentTarget.value === "error") {
10. onError(field.id, "Value shouldn't be equal to error");
11. } else {
12. onError(field.id, "");
13. }
14. onUpdate(field.id, event.currentTarget.value);
15. }}), " 🎉"
16. )
17. );
18. }
19. }
Here, the input
element will fire the onChange event when it updates. (line 8)
In React.createElement
this is passed along to onUpdate
after some validation (line 14).
onCustomRender
will then set the value of this.properties.customFieldId
to the updated value.
You will have to check the properties of the component you are using to see how this is done for that and adjust your React.createElement
accordingly...