ReactContainer.tsx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import { Provider } from 'react-redux';
  4. import coreModule from 'app/core/core_module';
  5. import { store } from 'app/store/store';
  6. import { ContextSrv } from 'app/core/services/context_srv';
  7. function WrapInProvider(store, Component, props) {
  8. return (
  9. <Provider store={store}>
  10. <Component {...props} />
  11. </Provider>
  12. );
  13. }
  14. /** @ngInject */
  15. export function reactContainer(
  16. $route,
  17. $location,
  18. $injector,
  19. $rootScope,
  20. contextSrv: ContextSrv
  21. ) {
  22. return {
  23. restrict: 'E',
  24. template: '',
  25. link(scope, elem) {
  26. // Check permissions for this component
  27. const { roles } = $route.current.locals;
  28. if (roles && roles.length) {
  29. if (!roles.some(r => contextSrv.hasRole(r))) {
  30. $location.url('/');
  31. }
  32. }
  33. let { component } = $route.current.locals;
  34. // Dynamic imports return whole module, need to extract default export
  35. if (component.default) {
  36. component = component.default;
  37. }
  38. const props = {
  39. $injector: $injector,
  40. $rootScope: $rootScope,
  41. $scope: scope,
  42. };
  43. ReactDOM.render(WrapInProvider(store, component, props), elem[0]);
  44. scope.$on('$destroy', () => {
  45. ReactDOM.unmountComponentAtNode(elem[0]);
  46. });
  47. },
  48. };
  49. }
  50. coreModule.directive('reactContainer', reactContainer);