Strip all styling from pasted text in DraftJS?
Asked Answered
Y

2

6

When pasting text from word or another source into draftjs the formatting comes along for the ride, I tried stripping the styling data like so:

onChange={(newEditorState) => {
                        const raw = convertToRaw(newEditorState.getCurrentContent())
                        for (let i = 0; i < raw.blocks.length; i++){
                            raw.blocks[i].type = "unstyled"
                        }
                        let newContent = convertFromRaw(raw)
                        newEditorState
                        const newState = EditorState.push(state, newContent, "change-block-type")

                        setState(newState)
                    }} />

Which worked except typing ended up being reversed on input after that, which was very confusing.

Yellowlegs answered 6/5, 2019 at 12:42 Comment(0)
A
8

It seems like the stripPastedStyles option is what you're looking for:

Set whether to remove all information except plaintext from pasted content.

This should be used if your editor does not support rich styles.

Default is false.

Aguilar answered 6/5, 2019 at 15:7 Comment(0)
P
3

Another interesting find:

The handlepastedtext option can help to remove formatting that is not enabled within your editor.

Use it like this

<Editor
    // ...
    handlePastedText={() => false}
/>

Doing this, will for example keep bold text, headings, links, images etc which are enabled within your RTE, but will remove unrequired background styles, font-styles, etc.

Hope that helps!

Posit answered 23/6, 2023 at 10:6 Comment(1)
Nice feature, but seems like it only works for inline styles, but not for block styles.Acinus

© 2022 - 2024 — McMap. All rights reserved.