react.mdx 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. ---
  2. slug: /react
  3. ---
  4. import Tabs from '@theme/Tabs';
  5. import TabItem from '@theme/TabItem';
  6. # React
  7. [React][] components for the Uppy UI plugins and hooks.
  8. ## Install
  9. <Tabs>
  10. <TabItem value="npm" label="NPM" default>
  11. ```shell
  12. npm install @uppy/react
  13. ```
  14. </TabItem>
  15. <TabItem value="yarn" label="Yarn">
  16. ```shell
  17. yarn add @uppy/react
  18. ```
  19. </TabItem>
  20. </Tabs>
  21. :::note
  22. You also need to install the UI plugin you want to use. For instance,
  23. `@uppy/dashboard`.
  24. :::
  25. ## Use
  26. `@uppy/react` exposes component wrappers for `Dashboard`, `DragDrop`, and all
  27. other UI elements. The components can be used with either [React][] or
  28. API-compatible alternatives such as [Preact][].
  29. :::caution
  30. If you find yourself writing many instances of `useState` and `useEffect` to
  31. achieve something with Uppy in React, you are most likely breaking React best
  32. practices. Consider reading
  33. “[You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)”
  34. and looking at our examples below.
  35. :::
  36. ### Components
  37. The following components are exported from `@uppy/react`:
  38. - `<Dashboard />` renders [`@uppy/dashboard`](/docs/dashboard)
  39. - `<DragDrop />` renders [`@uppy/drag-drop`](/docs/drag-drop)
  40. - `<ProgressBar />` renders [`@uppy/progress-bar`](/docs/progress-bar)
  41. - `<StatusBar />` renders [`@uppy/status-bar`](/docs/status-bar)
  42. ### Hooks
  43. #### `useUppyState(uppy, selector)`
  44. Use this hook when you need to access Uppy’s state reactively. Most of the
  45. times, this is needed if you are building a custom UI for Uppy in React.
  46. ```js
  47. // IMPORTANT: passing an initializer function to prevent Uppy from being reinstantiated on every render.
  48. const [uppy] = useState(() => new Uppy());
  49. const files = useUppyState(uppy, (state) => state.files);
  50. const totalProgress = useUppyState(uppy, (state) => state.totalProgress);
  51. // We can also get specific plugin state.
  52. // Note that the value on `plugins` depends on the `id` of the plugin.
  53. const metaFields = useUppyState(
  54. uppy,
  55. (state) => state.plugins?.Dashboard?.metaFields,
  56. );
  57. ```
  58. You can see all the values you can access on the
  59. [`State`](https://github.com/transloadit/uppy/blob/c45407d099d87e25cecaf03c5d9ce59c582ca0dc/packages/%40uppy/core/src/Uppy.ts#L155-L181)
  60. type. If you are accessing plugin state, you would have to look at the types of
  61. the plugin.
  62. #### `useUppyEvent(uppy, event, callback)`
  63. Listen to Uppy events in a React component.
  64. The first item in the array is an array of results from the event. Depending on
  65. the event, that can be empty or have up to three values. The second item is a
  66. function to clear the results. Values remain in state until the next event (if
  67. that ever comes). Depending on your use case, you may want to keep the values in
  68. state or clear the state after something else happenend.
  69. ```ts
  70. // IMPORTANT: passing an initializer function to prevent Uppy from being reinstantiated on every render.
  71. const [uppy] = useState(() => new Uppy());
  72. const [results, clearResults] = useUppyEvent(uppy, 'transloadit:result');
  73. const [stepName, result, assembly] = results; // strongly typed
  74. useUppyEvent(uppy, 'cancel-all', clearResults);
  75. ```
  76. ## Examples
  77. ### Example: basic component
  78. Here we have a basic component which ties Uppy’s state to the component. This
  79. means you can render multiple instances. But be aware that as your component
  80. unmounts, for instance because the user navigates to a different page, Uppy’s
  81. state will be lost and uploads will stop.
  82. :::note
  83. If you render multiple instances of Uppy, make sure to give each instance a
  84. unique `id`.
  85. :::
  86. ```js
  87. import React, { useEffect, useState } from 'react';
  88. import Uppy from '@uppy/core';
  89. import Webcam from '@uppy/webcam';
  90. import { Dashboard } from '@uppy/react';
  91. import '@uppy/core/dist/style.min.css';
  92. import '@uppy/dashboard/dist/style.min.css';
  93. import '@uppy/webcam/dist/style.min.css';
  94. function Component() {
  95. // IMPORTANT: passing an initializer function to prevent Uppy from being reinstantiated on every render.
  96. const [uppy] = useState(() => new Uppy().use(Webcam));
  97. return <Dashboard uppy={uppy} />;
  98. }
  99. ```
  100. ### Example: keep Uppy state and uploads while navigating between pages
  101. When you want Uppy’s state to persist and keep uploads running between pages,
  102. you can
  103. [lift the state up](https://react.dev/learn/sharing-state-between-components#lifting-state-up-by-example).
  104. ```js
  105. import React, { useState, useEffect } from 'react';
  106. import Uppy from '@uppy/core';
  107. import { Dashboard } from '@uppy/react';
  108. function Page1() {
  109. // ...
  110. }
  111. function Page2({ uppy }) {
  112. return (
  113. <>
  114. <p>{totalProgress}</p>
  115. <Dashboard id="dashboard" uppy={uppy} />
  116. </>
  117. );
  118. }
  119. export default function App() {
  120. // keeping the uppy instance alive above the pages the user can switch during uploading
  121. const [uppy] = useState(() => new Uppy());
  122. return (
  123. // Add your router here
  124. <>
  125. <Page1 />
  126. <Page2 uppy={uppy} />
  127. </>
  128. );
  129. }
  130. ```
  131. ### Example: updating Uppy’s options dynamically based on props
  132. ```js
  133. // ...
  134. function Component(props) {
  135. // IMPORTANT: passing an initializer function to prevent the state from recreating.
  136. const [uppy] = useState(() => new Uppy().use(Webcam));
  137. useEffect(() => {
  138. uppy.setOptions({ restrictions: props.restrictions });
  139. }, [props.restrictions]);
  140. useEffect(() => {
  141. uppy.getPlugin('Webcam').setOptions({ modes: props.webcamModes });
  142. }, [props.webcamModes]);
  143. return <Dashboard uppy={uppy} />;
  144. }
  145. ```
  146. ### Example: dynamic params and signature for Transloadit
  147. When you go to production always make sure to set the `signature`. **Not using
  148. [Signature Authentication](https://transloadit.com/docs/topics/signature-authentication/)
  149. can be a security risk**. Signature Authentication is a security measure that
  150. can prevent outsiders from tampering with your Assembly Instructions.
  151. Generating a signature should be done on the server to avoid leaking secrets. In
  152. React, this could get awkward with a `fetch` in a `useEffect` and setting it to
  153. `useState`. Instead, it’s easier to use the
  154. [`assemblyOptions`](/docs/transloadit#assemblyoptions) option to `fetch` the
  155. params.
  156. ```js
  157. // ...
  158. function createUppy(userId) {
  159. return new Uppy({ meta: { userId } }).use(Transloadit, {
  160. async assemblyOptions(file) {
  161. // You can send meta data along for use in your template.
  162. // https://transloadit.com/docs/topics/assembly-instructions/#form-fields-in-instructions
  163. const body = JSON.stringify({ userId: file.meta.userId });
  164. const res = await fetch('/transloadit-params', { method: 'POST', body });
  165. return response.json();
  166. },
  167. });
  168. }
  169. function Component({ userId }) {
  170. // IMPORTANT: passing an initializer function to prevent Uppy from being reinstantiated on every render.
  171. const [uppy] = useState(() => createUppy(userId));
  172. useEffect(() => {
  173. if (userId) {
  174. // Adding to global `meta` will add it to every file.
  175. uppy.setOptions({ meta: { userId } });
  176. }
  177. }, [uppy, userId]);
  178. }
  179. ```
  180. [react]: https://facebook.github.io/react
  181. [preact]: https://preactjs.com/