Source: Inject.component.js

  1. import PropTypes from 'prop-types';
  2. import componentAPI from './component';
  3. import { useCMFContext } from './useContext';
  4. /**
  5. * The Inject component let you use the registry to render named component
  6. * using the registry. It will not break the app if component is not found
  7. * but it will display an error.
  8. * @module react-cmf/lib/Inject
  9. * @example
  10. import { Inject } from '@talend/react-cmf';
  11. // this is not the best example but it show the concept
  12. function MyComponent(props) {
  13. return (
  14. <Inject component="Action" onClick={props.onClick}>
  15. <Inject component="Icon" icon={props.icon} />
  16. </Inject>
  17. );
  18. }
  19. */
  20. function NotFoundComponent({ error }) {
  21. // eslint-disable-next-line no-console
  22. console.error(error);
  23. return <div className="alert alert-danger">{error.message}</div>;
  24. }
  25. NotFoundComponent.propTypes = {
  26. error: PropTypes.string.isRequired,
  27. };
  28. function Inject({ component, ...props }) {
  29. const context = useCMFContext();
  30. try {
  31. const Component = componentAPI.get(component, context);
  32. return <Component {...props} />;
  33. } catch (error) {
  34. return <NotFoundComponent error={error} />;
  35. }
  36. }
  37. Inject.propTypes = {
  38. component: PropTypes.string.isRequired,
  39. };
  40. Inject.NotFoundComponent = NotFoundComponent;
  41. export default Inject;