Creating a table with pagination in a Node Edit form

I have a content type article that has a field for Category. In order to help our editors find related articles, I included a table on the article Edit page that pulls in other article entities that have the same category as the current one.

I did this by implementing a hook_form_alter hook and adding some markup to the $ form object after querying for all related articles.

// Query for matching articles $  query = \Drupal::entityQuery('node'); $  query->condition('type', 'article'); $  query->condition('field_articles_category.entity:taxonomy_term.tid', $  categoryId); $  query->sort('created', $  sortDirection); $  query->range($  offset, $  limit); $  query->latestRevision();  /* Omitting logic to load the Node objects by revision ID's */ // $  articles is an array of Node objects of type article  $  articlesTable = [] foreach ($  articles as $  index => $  article) {    $  articlesTable[$  index] ['articleTitle'] = [       '#type' => 'link', '#title' => $  article->getTitle(), '#url' => $  article->toUrl()    ] }  $  form['related_articles'] = [    '#type' => 'details',    '#title' => 'Articles of the Same category',    'articlesTable' => $  articlesTable ]; 

The table displays just fine and shows the expected articles. But there are sometimes hundreds of articles in a particular category so I would like to paginate this table for performance reasons (and to make sure the page is not too long to scroll through). How can I paginate such a table?

I’ve seen some articles mention creating a pagination controller and somehow setting the AJAX callback for that controller, but haven’t found a concrete example yet to follow.