ReactContainer.tsx 1.6 KB

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