Creating custom React components | laravel-medialibrary | Spatie

 SPATIE

  Laravel Media Library
========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-medialibrary](https://spatie.be/docs/laravel-medialibrary/v9)  Handling-uploads-with-media-library-pro  Creating custom React components

 Version   v11   v10   v9   v8   v7   v6   v5   v4   v3

 Other versions for crawler [v11](https://spatie.be/docs/laravel-medialibrary/v11) [v10](https://spatie.be/docs/laravel-medialibrary/v10) [v9](https://spatie.be/docs/laravel-medialibrary/v9) [v8](https://spatie.be/docs/laravel-medialibrary/v8) [v7](https://spatie.be/docs/laravel-medialibrary/v7) [v6](https://spatie.be/docs/laravel-medialibrary/v6) [v5](https://spatie.be/docs/laravel-medialibrary/v5) [v4](https://spatie.be/docs/laravel-medialibrary/v4) [v3](https://spatie.be/docs/laravel-medialibrary/v3)

- [ Introduction ](https://spatie.be/docs/laravel-medialibrary/v9/introduction)
- [ Support us ](https://spatie.be/docs/laravel-medialibrary/v9/support-us)
- [ Base installation ](https://spatie.be/docs/laravel-medialibrary/v9/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-medialibrary/v9/questions-issues)
- [ Requirements ](https://spatie.be/docs/laravel-medialibrary/v9/requirements)
- [ Upgrading ](https://spatie.be/docs/laravel-medialibrary/v9/upgrading)
- [ Changelog ](https://spatie.be/docs/laravel-medialibrary/v9/changelog)
- [ Troubleshooting ](https://spatie.be/docs/laravel-medialibrary/v9/troubleshooting)
- [ About us ](https://spatie.be/docs/laravel-medialibrary/v9/about-us)

Basic usage
-----------

- [ Preparing your model ](https://spatie.be/docs/laravel-medialibrary/v9/basic-usage/preparing-your-model)
- [ Associating files ](https://spatie.be/docs/laravel-medialibrary/v9/basic-usage/associating-files)
- [ Retrieving media ](https://spatie.be/docs/laravel-medialibrary/v9/basic-usage/retrieving-media)

Working with media collections
------------------------------

- [ Simple media collections ](https://spatie.be/docs/laravel-medialibrary/v9/working-with-media-collections/simple-media-collections)
- [ Defining media collections ](https://spatie.be/docs/laravel-medialibrary/v9/working-with-media-collections/defining-media-collections)

Converting images
-----------------

- [ Defining conversions ](https://spatie.be/docs/laravel-medialibrary/v9/converting-images/defining-conversions)
- [ Retrieving converted images ](https://spatie.be/docs/laravel-medialibrary/v9/converting-images/retrieving-converted-images)
- [ Optimizing converted images ](https://spatie.be/docs/laravel-medialibrary/v9/converting-images/optimizing-converted-images)
- [ Regenerating images ](https://spatie.be/docs/laravel-medialibrary/v9/converting-images/regenerating-images)

Handling uploads with Media Library Pro
---------------------------------------

- [ Introduction ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/introduction)
- [ Installation ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/installation)
- [ Processing uploads on the server ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/processing-uploads-on-the-server)
- [ Handling uploads with Blade ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/handling-uploads-with-blade)
- [ Handling uploads with Livewire ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/handling-uploads-with-livewire)
- [ Handling uploads with Vue ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/handling-uploads-with-vue)
- [ Handling uploads with React ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/handling-uploads-with-react)
- [ Creating custom Vue components ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/creating-custom-vue-components)
- [ Creating custom React components ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/creating-custom-react-components)
- [ Customizing CSS ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/customizing-css)

Responsive images
-----------------

- [ Getting started with responsive images ](https://spatie.be/docs/laravel-medialibrary/v9/responsive-images/getting-started-with-responsive-images)
- [ Using your own width calculator ](https://spatie.be/docs/laravel-medialibrary/v9/responsive-images/using-your-own-width-calculator)
- [ Customizing the rendered html ](https://spatie.be/docs/laravel-medialibrary/v9/responsive-images/customizing-the-rendered-html)
- [ Generating your own tiny placeholder ](https://spatie.be/docs/laravel-medialibrary/v9/responsive-images/generating-your-own-tiny-placeholder)
- [ Responsive images demo ](https://spatie.be/docs/laravel-medialibrary/v9/responsive-images/demo)

Converting other file types
---------------------------

- [ Using image generators ](https://spatie.be/docs/laravel-medialibrary/v9/converting-other-file-types/using-image-generators)
- [ Creating a custom image generator ](https://spatie.be/docs/laravel-medialibrary/v9/converting-other-file-types/creating-a-custom-image-generator)

Downloading media
-----------------

- [ Downloading a single file ](https://spatie.be/docs/laravel-medialibrary/v9/downloading-media/downloading-a-single-file)
- [ Downloading multiple files ](https://spatie.be/docs/laravel-medialibrary/v9/downloading-media/downloading-multiple-files)

Advanced usage
--------------

- [ Working with multiple filesystems ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/working-with-multiple-filesystems)
- [ Using custom properties ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/using-custom-properties)
- [ Storing media specific manipulations ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/storing-media-specific-manipulations)
- [ Using your own model ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/using-your-own-model)
- [ Outputting media ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/outputting-media)
- [ Rendering media ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/rendering-media)
- [ Using a custom directory structure ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/using-a-custom-directory-structure)
- [ Ordering media ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/ordering-media)
- [ Using a custom media downloader ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/using-a-custom-media-downloader)
- [ Moving media ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/moving-media)
- [ Consuming events ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/consuming-events)
- [ Generating custom urls ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/generating-custom-urls)
- [ Overriding default filesystem behavior ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/overriding-the-default-filesystem-behaviour)
- [ Naming generated files ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/naming-files)
- [ Disable CDN ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/disable-cdn)
- [ Customising Database Connections ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/customising-database-connections)

API
---

- [ Adding files ](https://spatie.be/docs/laravel-medialibrary/v9/api/adding-files)
- [ Defining conversions ](https://spatie.be/docs/laravel-medialibrary/v9/api/defining-conversions)

      You are viewing the documentation for **an older version** of this package. You can check the version you are using with the following command:

 `                                    composer show spatie/laravel-medialibrary                                                                                                                                                                                                                                    `

Creating custom React components
================================

###  On this page

1. [ Getting started ](#content-getting-started)
2. [ Examples ](#content-examples)
3. [ Helper components ](#content-helper-components)
4. [ Parameters ](#content-parameters)
5. [ Returned variables ](#content-returned-variables)

Both the Vue and React UI components are built on top of the same core, with a language-specific abstraction layer in between that exposes some helper functions. You can extend the core that the UI components are built on. This allows you to customize the UI. This page will go into detail about these abstraction layers.

To create your own UI components that hook into the Media Library Pro JS core, you can use the `useMediaLibrary` hook in a functional component. If you are building a class component, there are several tutorials available online on how to wrap a custom hook in a higher-order component for use in class components.

For more extensive examples, [see the pre-built UI components on GitHub](https://github.com/spatie/laravel-medialibrary-pro/blob/master/resources/js)

Getting started
-----------------------------------------------------------------------------------------------------

```
import * as React from "react";
import { useMediaLibrary } from "media-library-pro-react";

export default function MediaLibraryAttachment() {
    const {
        state,
        getImgProps,
        getFileInputProps,
        getDropZoneProps,
        removeMedia,
        setOrder,
        replaceMedia,
        getErrors,
        clearObjectErrors,
        clearInvalidMedia,
        isReadyToSubmit,
    } = useMediaLibrary({
        initialMedia: initialValue,
        validationErrors,
        routePrefix,
        validationRules,
        multiple,
        beforeUpload,
        afterUpload,
        onChange,
    });

    return (

            {state.media.map((object) => (

            ))}

    );
}
```

You can find a full list of available parameters and exposed variables for the hook [at the bottom of this page](#parameters).

Examples
--------------------------------------------------------------------------------

For extensive examples you can have a look at the source of the pre-built UI components:

- [React collection component](https://github.com/spatie/laravel-medialibrary-pro/tree/master/resources/js/media-library-pro-react-attachment)
- [React collection component](https://github.com/spatie/laravel-medialibrary-pro/tree/master/resources/js/media-library-pro-react-collection)

Helper components
-----------------------------------------------------------------------------------------------------------

When building your own UI component using the Media Library Pro, you can also make use of these helper components. These are the same components that are used in the UI components.

### DropZone

[See code on GitHub](https://github.com/spatie/laravel-medialibrary-pro/blob/master/resources/js/media-library-pro-react/src/DropZone.tsx)

Renderless component that exposes some props needed to render a file dropzone.

**props**

```
{
    validationAccept?: MediaLibrary.Config["validationRules"]["accept"];
    children: ({
        hasDragObject,
        isDropTarget,
    }: {
        hasDragObject: boolean;
        isDropTarget: boolean;
        isValid: boolean;
    }) => React.ReactNode;
    onDrop: (event: React.DragEvent) => void;
} & React.DetailedHTMLProps;
```

### HiddenFields

[See code on GitHub](https://github.com/spatie/laravel-medialibrary-pro/blob/master/resources/js/media-library-pro-react/src/HiddenFields.tsx)

Component that renders hidden input fields with the values of the entire MediaLibrary instance's media state. Only needed if you're planning on submitting forms traditionally (not with AJAX).

**props**

```
{
    name: string;
    mediaState: MediaLibrary.State["media"];
}
```

### ItemErrors

[See code on GitHub](https://github.com/spatie/laravel-medialibrary-pro/blob/master/resources/js/media-library-pro-react/src/ItemErrors.tsx)

Component that renders the errors for one media object.

**props**

```
{
    objectErrors: string[];
    onBack?: (e: React.MouseEvent) => void;
}
```

### ListErrors

[See code on GitHub](https://github.com/spatie/laravel-medialibrary-pro/blob/master/resources/js/media-library-pro-react/src/ListErrors.tsx)

Component that can render the MediaLibrary instance's invalid media (`mediaLibrary.state.invalidMedia`).

**props**

```
{
    invalidMedia: MediaLibrary.State["invalidMedia"];
    topLevelErrors?: Array;
    onClear: () => void;
}
```

### Thumb

[See code on GitHub](https://github.com/spatie/laravel-medialibrary-pro/blob/master/resources/js/media-library-pro-react/src/Thumb.tsx)

Component to display a file's thumbnail. If no preview for the file exists, it will attempt to display its extension. Also implements the [Uploader](#uploader) component to replace files.

**props**

```
{
    uploadInfo: MediaLibrary.MediaObject["upload"];
    validationRules?: Partial;
    imgProps: {
        src: string | undefined;
        alt: string;
        extension: string | undefined;
    };
    onReplace: (file: File) => void;
}
```

### Uploader

[See code on GitHub](https://github.com/spatie/laravel-medialibrary-pro/blob/master/resources/js/media-library-pro-react/src/Uploader.tsx)

Component used to upload new media objects, or to replace an existing object's file. Is used by the [Thumb](#thumb) component.

**props**

```
{
    add?: boolean;
    uploadInfo?: MediaLibrary.MediaObject["upload"];
    multiple: boolean;
    validationRules?: Partial;
    maxItems?: number;
    fileTypeHelpText?: string;
    onDrop: (event: React.DragEvent) => void;
    onChange: (event: React.ChangeEvent) => void;
}
```

### Icons

[See code on GitHub](https://github.com/spatie/laravel-medialibrary-pro/blob/master/resources/js/media-library-pro-react/src/components/Icons.tsx)

Component that sets svg values for the packaged icons, required if you're planning on using the [icon](#icon) component.

### Icon

[See code on GitHub](https://github.com/spatie/laravel-medialibrary-pro/blob/master/resources/js/media-library-pro-react/src/components/Icon.tsx)

Renders an icon. Requires [icons](#icons) to be rendered on the page.

**Props**

```
{
    icon: string;
    className?: string;
}
```

### IconButton

[See code on GitHub](https://github.com/spatie/laravel-medialibrary-pro/blob/master/resources/js/media-library-pro-react/src/components/IconButton.tsx)

Renders a button with an icon. Requires [icons](#icons) to be rendered on the page.

**Props**

```
{
    icon: string;
    className?: string;
}
```

### useDragula

[See code on GitHub](https://github.com/spatie/laravel-medialibrary-pro/blob/master/resources/js/media-library-pro-react/src/useDragula.ts)

Custom hook to use [Dragula](https://github.com/bevacqua/react-dragula), to allow sorting of files.

**Parameters**

```
handleClass?: string
```

Parameters
--------------------------------------------------------------------------------------

parameter nameDefault valueDescriptionnameinitialValue`[]`routePrefix`"media-library-pro"`uploadDomainUse this if you're uploading your files to a separate (sub)domain, e.g. `files.mydomain.com` (leave out the trailing slash)validationRulesRefer to the ["validation"](./handling-uploads-with-react#validation-rules) sectionvalidationErrorsThe standard Laravel validation error objectmaxItemsmaxSizeForPreviewInBytestranslationsRefer to the ["Translations"](./handling-uploads-with-react#translations) sectionvapor`false`Set to true if you will deploy your application to Vapor, this enables uploading of the files to S3. [Read more](./handling-uploads-with-react#usage-with-laravel-vapor)vaporSignedStorageUrl`"vapor/signed-storage-url"`multiple`true`beforeUploadA method that is run right before a temporary upload is started. You can throw an `Error` from this function with a custom validation messageafterUploadA method that is run right after a temporary upload has completed, `{ success: true, uuid }`onChangeReturned variables
--------------------------------------------------------------------------------------------------------------

variable nameDescriptionmediaLibraryRef to the MediaLibrary instancestateThe state of the MediaLibrary instance. Includes `media` (an array of currently added files), `invalidMedia` (files that encountered a frontend validation error) and `validationErrors` (backend validation errors mapped to uuids)isReadyToSubmitBoolean that tells whether the MediaLibrary instance is ready to submit (has no uploads in progress and has no frontend validation errors)hasUploadsInProgressBoolean that tells whether the MediaLibrary instance currently has uploads in progressgetImgPropsMethod that expects a media object, and returns an object with props needed for an `img` taggetNameInputPropsMethod that expects a media object, and returns an object with props needed for an `input type=text` tag that controls an object's name attributegetNameInputErrorsMethod that expects a media object, and returns an array of backend validation errors for the `name` attributegetCustomPropertyInputPropsMethod that expects a media object, and a custom property name, and returns an object with props needed for an `input` tag that controls that custom propertygetCustomPropertyInputErrorsMethod that expects a media object, and a custom property name, and returns an array of backend validation errors for that custom propertygetFileInputPropsMethod that expects a media object, and returns an object with props needed for an `input type=file` tag that controls an object's name attributegetDropZonePropsMethod that expects a media object, and returns an object with props needed for a file dropzone (`onDrop`)addFileMethod that allows a user to pass in a File to be added to the MediaLibrary instance's media stateremoveMediaMethod that expects a media object, and removes it from the MediaLibrary instance's media statesetOrderMethod that expects an array of uuids, and sets the `order` attribute of the media objects in the media statesetPropertyMethod that expects a media object, a key (`client_preview`, `attributes.preview_url`, `attributes.size`, `attributes.extension` …), and a value, and sets this property on the media object. This method usually shouldn't be used outside of the coresetCustomPropertyMethod that expects a media object, a custom property key (`tags`, `caption`, `alt` …), and a value, and sets this property on the media objectreplaceMediaMethod that expects a media object and a File, and uploads this file and replaces it on the media objectgetErrorsMethod that expects a media object, and returns an array of errors that it may have encounteredclearObjectErrorsMethod that expects a media object, and clears its errorsclearInvalidMediaMethod that clears the MediaLibrary instance's invalidMedia state
