virtualdom.rst 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. .. _react:
  2. React
  3. =====
  4. Many JupyterLab APIs require `Lumino`
  5. `Widgets <https://jupyterlab.github.io/lumino/widgets/classes/widget.html>`__
  6. which have some additional features over native DOM elements, including:
  7. - Resize events that propagate down the Widget hierarchy.
  8. - Lifecycle events (``onBeforeDetach``, ``onAfterAttach``, etc.).
  9. - Both CSS-based and absolutely positioned layouts.
  10. We support wrapping React components to turn them into Lumino
  11. widgets using the ``ReactWidget`` class from ``@jupyterlab/apputils``:
  12. .. literalinclude:: virtualdom.create.tsx
  13. :force:
  14. Here we use the ``create`` static method to transform a React element
  15. into a Lumino widget. Whenever the widget is mounted, the React
  16. element will be rendered on the page.
  17. If you need to handle other life cycle events on the Lumino widget
  18. or add other methods to it, you can subclass ``ReactWidget`` and
  19. override the ``render`` method to return a React element:
  20. .. literalinclude:: virtualdom.reactwidget.tsx
  21. :force:
  22. We use Lumino `Signals <https://jupyterlab.github.io/lumino/signaling/interfaces/isignal.html>`__ to represent
  23. data that changes over time in JupyterLab.
  24. To have your React element change in response to a signal event, use the ``UseSignal`` component from ``@jupyterlab/apputils``,
  25. which implements the `"render props" <https://reactjs.org/docs/render-props.html>`__:
  26. .. literalinclude:: virtualdom.usesignal.tsx
  27. :force:
  28. The `running component <https://github.com/jupyterlab/jupyterlab/blob/f2e0cde0e7c960dc82fd9b010fcd3dbd9e9b43d0/packages/running/src/index.tsx#L157-L159>`__
  29. and the ``createSearchOverlay`` function in the `search overlay <https://github.com/jupyterlab/jupyterlab/blob/f2e0cde0e7c960dc82fd9b010fcd3dbd9e9b43d0/packages/documentsearch/src/searchoverlay.tsx#L440-L457>`__
  30. use both of these features and serve as a good reference for best practices.
  31. There is also a `simple example <https://github.com/jupyterlab/extension-examples/tree/71486d7b891175fb3883a8b136b8edd2cd560385/react/react-widget>`_ making
  32. a Lumino react widget in the JupyterLab `extension examples repository <https://github.com/jupyterlab/extension-examples>`_.
  33. We currently do not have a way of embedding Lumino widgets inside of React components. If you find yourself trying to do this, we would recommend either converting the Lumino widget to a React component or using a Lumino widget for the outer layer component.
  34. We follow the `React documentation <https://reactjs.org/docs/thinking-in-react.html>`__ and
  35. `"React & Redux in TypeScript - Static Typing Guide" <https://github.com/piotrwitek/react-redux-typescript-guide#readme>`__
  36. for best practices on using React in TypeScript.