Handling Pasted Content in Draft.js
Sometimes you've got to be a control freak. For those times, use Draft.js's handlePastedText hook for fine grain control over pasted content.
We use React for our client code at Blue Matador. A while ago, I needed to implement a text box for querying log entries (Blue Matador offers a centralized log management solution) and I wanted to highlight certain pieces of the query. Enter Draft.js, Facebook’s rich text editor framework.
I won’t go into the details about what Draft.js is (their website takes care of that), but I ran into a situation where users pasting in log entry data they got out of the viewer into the query box got some weird looking results because of HTML formatting:
As I looked for a way to get better control over what the pasted values would look like, I ran across a function called handlePastedText
in Editor
’s props. It turned out to be exactly what I needed, but I couldn’t seem to find any examples of using it. So here’s one I created (with Flow type annotations):
handlePastedText
takes two parameters:
- the plain text that the user pasted
- an HTML string as its second parameter if the text the user pasted was copied from HTML
Returning true
tells Draft.js that you’ve handled the pasted text and it will take no further action. Returning false
tells Draft.js to take the action it would have taken if handlePastedText
hadn’t been called. It’s a simple mechanism, but gives you a lot of power over pasted content.
Comments
Let me know what you think!