6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rails × react にfroala editorを導入してみる

Posted at

はじめに

もともとradactorというjqueryのwysiwyg editorをreactで使っていたが、安定性とreactとの相性から、reactのコンポーネントを提供してくれているfroalaという有料のwysiwyg editorを使うことにした。(こちらもjqueryが使われていることには変わりない)
https://www.froala.com/wysiwyg-editor
draft.jsも視野に入れたが、写真の挿入が簡単ということで、froalaを採用した。

セットアップ

react版とrails版があり、react版はwebpackの設定がややこしそうだったので、react版はコンポーネントを使うだけにとどめ、必要なjsとcssはgemでインストールしたwysiwyg-railsからimportした。(参考:https://www.froala.com/wysiwyg-editor/docs/framework-plugins/rails#include-in-assets)

これでreactのコンポーネントを呼び出すだけで、wysiwyg editorが動くようになる。

FroalaEditor

importがうまくいっていれば

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(<FroalaEditor tag='textarea'/>, document.getElementById('editor'));

だけで動くようになる

modelとconfig

formでいうvalueのようなものでhtmlが入る。これをstateで管理する、
変更があればonModelChangeでstateを更新する。この辺りは従来のinputとほぼ同じ。

class EditorComponent extends React.Component {
  constructor () {
    super();

    this.handleModelChange = this.handleModelChange.bind(this);

    this.state = {
      model: '<p>Example text</p>'
    };
  }

  handleModelChange(model) {
    this.setState({
      model: model
    });
  }

  render () {
    const self = this 
    const config = {
      placeholderText: 'テキストを追加',
      charCounterCount: false,
      theme: 'dark',
      zindex: 0,
      toolbarButtons:['bold', 'underline'],
      language: 'ja',
      imageUploadURL: /* railsに送るrequestのpath */,
      imageUploadParams: {
        // railsに送るparams
      },
      videoInsertButtons: ['videoBack', '|', 'videoByURL'],
      events: {
        'froalaEditor.blur': function() {
          self.handleSave()
        }
      }
    };
    return <FroalaEditor
              model={this.state.model}
              onModelChange={this.handleModelChange}
                  config={config}
           />
  }
}

またconfig内に設定を書くことができて、https://www.froala.com/wysiwyg-editor/docs/options と同じようにconfigのhashにどんどん書いていけばok
eventは上記のようにさらにeventのhashにcallbackを書いていけばよい。今回はblurで保存したかったので、https://www.froala.com/wysiwyg-editor/docs/events を参考にfroalaEditor.blurのcallbackでrailsにrequestを送った。

感想

日本ではあまり使われていないようだが、さすが有料ということもあり使いやすく高機能でデザインやUIも充実している。しかし、ドキュメントが英語しかないのと価格が1万ちょっとと手が出しにくい。しかし、無料でdownloadして試すことができるから、ぜひ一度試していただきたい。

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?