How to store rich-text in database
Asked Answered
T

3

5

I want to store data that is being edited with Draft.js and React (in the UI) into a MySQL database.

I am not sure in which format should I store my data, so that I can fetch the data from database and display it on the page with the formatting applied while writing the text?

For example - I applied bold style to some of the text and gave some line breaks. How to store this info for later use?

Please suggest a format to store my data.

Turboprop answered 19/12, 2018 at 6:53 Comment(1)
Sounds like you are reinventing GoogleDocs.Comeback
C
6

You could save it as a string format. To elaborate, you can use a JSON-serialized string of the ContentState as mentioned in the Draft JS docs.

Draft JS has utility methods convertFromRaw and convertToRaw to help you. Check out the docs linked above, they are pretty clear.

Colonel answered 20/12, 2018 at 8:21 Comment(0)
B
3

For anyone still facing this issue, basically you have to convertToRaw, then JSON.stringify it. Then this can be sent to your backend as a string. To display it, make a GET request for that particular data, then JSON.parse it and then convertFromRaw. Pass this into another RichTextEditor as the editorState but set the readOnly={true}

Benghazi answered 23/9, 2022 at 8:1 Comment(1)
convertToRaw is DraftJs function draftjs.org/docs/api-reference-data-conversion/#converttorawSunbow
M
1

Draft.js is archiving.

A new alternative is lexical

You can find its playground here: https://playground.lexical.dev/

Monas answered 25/1, 2023 at 1:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.