How to attach JS library in a view in Drupal 8?

JS library to a view can be attached using hook_views_pre_render(). Use the following code to achieve it:

/**
 * Implements hook_views_pre_render().
 */
function your_module_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'YOUR_VIEW_ID' && $view->current_display == 'YOUR_VIEW_DISPLAY') {
    $view->element['#attached']['library'][] = 'your_module/your_library';
  }
}

Tags