All Articles

Add ActionText with Trix rich text editor to React

Rich text editor is one of the common requirement of most of the web application. Addition of Rich text editor in React is very easy. A lot of popular libraries help achieve the rich text content editing in React. The problem is addition of images, videos or documents in these libraries(the most I have used so far I faced the issue).

Problem Statement:

  • Addition of videos to the rich text editor, you need to add the embed video links and cannot upload the videos directly or drop them in the editor.
  • The another problem is to store the images, documents for the rich text in the database and properly managing them.

The solution to the problems is to use Action Text with Trix Editor in React.

How to add Trix to React?

Trix editor does not have any React wrapper or package to easily add Trix to our application. You can create simple React component as per your need to add the Trix editor.

I did that multiple times in couple of projects and thought its time to create a NPM package to easily add Trix editor. Here is the link to the React-Trix-RTE package and the live demo

ReactTrixRTE

Awesome! We have Action Text Trix editor in our application.

Some commonly faced problems in the Action Text Trix editor

Let’s say we have Message model which consist of Action Text content

# app/models/message.rb
class Message < ApplicationRecord
  has_rich_text :content
end

1. How to Pre-populate Trix editor with Action Text content?

Use message.content.body.to_trix_html.

2. How to view the Action Text content in React?

Use message.content.to_s.

3. How to direct upload files via Action Text Trix editor to Active Storage?

Set the direct upload URL and blob template URL for the Trix editor.

<trix-editor
  ...
  data-direct-upload-url="/rails/active_storage/direct_uploads"
  data-blob-url-template="/rails/active_storage/blobs/:signed_id/*filename"
/>

If you are using React-Trix-RTE. Passing isRailsDirectUpload prop to true set the default direct upload URLs for Rails and uploads the attached files to Active Storage directly.

4. How to fix the multiple figcaptions added by Trix editor and Action Text?

When Action Text is installed, Rails by default adds the views/active_storage/blobs/_blob.html.erb. Removing the figcaption from the _blob.html.erb should remove unnecessary multiple figcaptions getting added in Action Text.

5. PDF or Video previews in Action Text

Active Storage preview depends on the third party libraries. For PDF, you can download Poppler or muPDF. For videos, you can download FFmpeg.

Rails throws errors if the videos and PDFs are added as attachment to Action Text.

Happy Coding!!