Skip to content

Instantly share code, notes, and snippets.

@mecmartini
Created February 4, 2021 19:39
Show Gist options
  • Save mecmartini/891fab1fe476d14f2a6b4683d769387a to your computer and use it in GitHub Desktop.
Save mecmartini/891fab1fe476d14f2a6b4683d769387a to your computer and use it in GitHub Desktop.
Drupal and React - Field Formatter
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$id = $items->getEntity()->id();
# Generate a wrapper to use as dom root to attach the React component.
$field_name = $this->fieldDefinition->getItemDefinition()->getFieldDefinition()->getName();
$wrapper_id = 'drupal-and-react-app-' . $field_name .'-'. $id;
$build = [
'#markup' => '<div id="' . $wrapper_id . '"></div>',
];
# Get field items and values.
foreach ($items as $delta => $item) {
$elements[$delta] = $item->value;
}
# Attach the React component to the field formatter.
$build['#attached']['library'] = [
'drupal_and_react/app_bundle',
];
# Send the required data to the React component via Drupal settings.
$build['#attached']['drupalSettings']['drupal_and_react_app'][$id] = [
'id' => $id,
'wrapper' => $wrapper_id,
'content' => $elements,
];
return $build;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment