How can I add a class to a nav menu when I’m viewing a child page?

I figured out a way.

I changed the if statement to

 if (in_array('current-menu-item', $classes) || 
     in_array('current-page-ancestor', $classes)) {
          $classes[] = 'active ';
     }