In your THEMENAME.theme file, add the following code:

Implements hook_preprocess_menu()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * Implements hook_preprocess_menu().
 */
function THEMENAME_preprocess_menu(&$variables, $hook) {
  if ($hook == 'menu__main') { // We're doing that for main menu.
    // Get the current path.
    $current_path = \Drupal::request()->getRequestUri();
    $items = $variables['items'];
    foreach ($items as $key => $item) {
      // If path is current_path, set active to li.
      if ($item['url']->toString() == $current_path) {
        // Add active link.
        $variables['items'][$key]['attributes']['class'] = 'active';
      }
    }
  }
}