react.mdx 6.9 KB

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