Search code examples
ruby-on-railsjstreewebpacker

How to add jstree via webpacker to Rails


I have a Rails 6 app where I added jstree library via yarn. I have application.js file where are the require statement. I want to do the following $('#tree').jstree(); but this results in function jstree undefined exception. How should I require it?


Solution

  • Create a new Rails app:

    rails new myapp
    cd myapp
    

    Install jstree and jQuery (which it depends upon):

    yarn add jstree jquery
    

    Create a new controller and view:

    rails g controller welcome index
    

    Start the dev server and the Rails server:

    ./bin/webpack-dev-server
    rails s
    

    In packs/application.js:

    require('../../../node_modules/jstree/dist/themes/default/style.min.css');
    global.$ = require('jquery');
    require('jstree');
    
    $(() => {
      $('#jstree').jstree();
    });
    

    Add some HTML to welcome#index:

    <div id="jstree">
      <ul>
        <li>Root node 1
          <ul>
            <li id="child_node_1">Child node 1</li>
            <li>Child node 2</li>
          </ul>
        </li>
        <li>Root node 2</li>
      </ul>
    </div>
    

    Visit http://localhost:3000/welcome/index to see jstree in action.

    HTH