wanna_coder101
wanna_coder101

Reputation: 186

How to change property of SlateJS node element onChange?

How to change Node element property in SlateJS OnChange method?

I have an initial element like before, notice the 'id' property? In OnChange, I want dynamically set the id property. See below for implementation, more or less just SlateJs's basic react setup

const initialValue: Descendant[] = [
    {
        type: 'paragraph',
        id: '',
        children: [
            {
                text:
                    'This is editable plain text, just like a <textarea>!',
            },
        ],
    },
]

Slate React Component

        <Slate
            editor={editor}
            value={textContent}
            onChange={currTextContent => {
                // Logic for newlines
                if (currTextContent.length > textContent.length) {
                    // Same example from slatejs on how to save content
                    const isAstChange = editor.operations.some(
                        op => 'set_selection' !== op.type,
                    )

                    if (isAstChange) {
                        // Set id property of new line
                        currTextContent[0].id = 'test'
                    }
                }

                settextContent(currTextContent)
            }}>
            <Editable
                placeholder="Enter some rich text…"
                spellCheck
                autoFocus
            />
        </Slate>

However, it says the .id property is readonly. The same story happens if I were to try and set the entire object. It's readonly. Adding new properties via currTextContent[0].newID also gives an error, object is not extensible

                    currTextContent[0] = {
                        type: 'paragraph',
                        id: '',
                        children: [
                            {
                                text:
                                    'This is editable plain text, just like a <textarea>!',
                            },
                        ],
                    }

How can I change (or add) SlateJS Node's element property in the onChange method? Is there some function to do this in the Editor class?

Upvotes: 2

Views: 4631

Answers (1)

wanna_coder101
wanna_coder101

Reputation: 186

So you can't actually change the nodes in onChange as they're readonly. Instead, you'll need to use the Slate API transform, to insert or add new properties like below.

    Transforms.setNodes(
        editor,
        {
            id: '123',
        },
        { at: [0] },
    )

That would insert the property, id = 123, into node[0].

Upvotes: 3

Related Questions