virtualdom.rst 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. .. _react:
  2. React
  3. -----
  4. Many JupyterLab APIs require `Phosphor <https://phosphorjs.github.io/>`__
  5. `Widgets <https://phosphorjs.github.io/phosphor/api/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 Phosphor
  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 Phosphor 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 Phosphor widget
  18. or add other methods to it, you can subbclass ``ReactWidget`` and
  19. override the ``render`` method to return a React element:
  20. .. literalinclude:: virtualdom.reactwidget.tsx
  21. :force:
  22. We use Phosphor `Signals <https://phosphorjs.github.io/phosphor/api/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,
  25. which implements the `"render props" <https://reactjs.org/docs/render-props.html>`__.
  26. The `running component <https://github.com/jupyterlab/jupyterlab/blob/master/packages/running/src/index.tsx>`__
  27. and the ``createSearchOverlay`` function in the `search overlay <https://github.com/jupyterlab/jupyterlab/blob/master/packages/documentsearch/src/searchoverlay.tsx>`__
  28. use both of these features and serve as a good reference for best practices.
  29. We follow the `React documentation <https://reactjs.org/docs/thinking-in-react.html>`__ and
  30. `"React & Redux in TypeScript - Static Typing Guide" <https://github.com/piotrwitek/react-redux-typescript-guide#readme>`__
  31. for best practices on using React in TypeScript.