How to display image preview right away for managed_file form element? I have managed_file for uploading an image in my form and I would like to display the image(thumbnail) right away when the user uploads it so he won' have to submit the form to see it(I am rendering it in the form if the image exists).

I think there might be an issue with the ajax wrapper/structure so I am not sure how exactly it should be achieved without too much customization/coding.
This is my solution:

&lt;?php

namespace Drupal\foo\Element;

use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Element\ManagedFile;

/**
 * @FormElement("managed_image")
 */
class ManagedImage extends ManagedFile {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $info = parent::getInfo();
    // @see \Drupal\image\Plugin\Field\FieldWidget\ImageWidget::formElement()
    $info['#accept'] = 'image/*';
    $info['#image_style'] = 'thumbnail';

    return $info;
  }

  /**
   * {@inheritdoc}
   */
  public static function processManagedFile(&amp;$element, FormStateInterface $form_state, &amp;$complete_form) {
    /** @var \Drupal\Core\Image\ImageFactory $image_factory */
    $image_factory = \Drupal::service('image.factory');
    $element['#upload_validators'] += [
      'file_validate_is_image' =&gt; [],
      'file_validate_extensions' =&gt; [implode(' ', $image_factory-&gt;getSupportedExtensions())]
    ];

    $element['#description'] = [
      '#theme' =&gt; 'file_upload_help',
      '#description' =&gt; isset($element['#description']) ? $element['#description'] : NULL,
      '#upload_validators' =&gt; $element['#upload_validators']
    ];

    return parent::processManagedFile($element, $form_state, $complete_form);
  }

  /**
   * {@inheritdoc}
   */
  public static function preRenderManagedFile($element) {
    $element = parent::preRenderManagedFile($element);

    if (!empty($element['#files'])) {
      foreach ($element['#files'] AS $delta =&gt; $file) {
        /** @var \Drupal\file\Entity\File $file */
        $element['file_' . $delta] = [
          'preview' =&gt; [
            '#type' =&gt; 'container',
            '#weight' =&gt; -10,
            '#attributes' =&gt; [
              'class' =&gt; [
                'image-preview'
              ]
            ],
            'image' =&gt; [
              '#theme' =&gt; 'image_style',
              '#style_name' =&gt; $element['#image_style'],
              '#uri' =&gt; $file-&gt;getFileUri()
            ]
          ]
        ] + $element['file_' . $delta];
      }
    }

    return $element;
  }

}