diff --git a/ptoc.module b/ptoc.module
index 887eefdb7226efdb42f607e3bcc770ca2818894b..39824be5fcd8280b3f8ea1fe0545c6784a7c6c4c 100644
--- a/ptoc.module
+++ b/ptoc.module
@@ -38,8 +38,10 @@ function ptoc_help($route_name, RouteMatchInterface $route_match) {
  * link to it from the table of contents.
  */
 function ptoc_preprocess_paragraph(&$variables) {
-  if ('default' == $variables['elements']['#view_mode']) {
-    $variables['attributes']['id'] = 'paragraph-' . $variables['paragraph']->id();
+  // Generate an id attribute for paragraphs in the default view mode unless
+  // they already have one.
+  if ($variables['elements']['#view_mode'] === 'default') {
+    $variables['attributes']['id'] ??= 'paragraph-' . $variables['paragraph']->id();
   }
   if ($variables['elements']['#view_mode'] === 'ptoc') {
     // Let the Twig template know which field to use for the link text.