Skip to main content

Render React Components Inside Angular

We use a library called ng-react to render React components inside of Angular. All components that are to be rendered in Angular are exported from src/app-index.js. All exports from this file are added to window.SLApp at runtime. This is important as components are rendered using this global variable reference.

Limitations

Each component rendered this way is technically its own separate React application instance. The React components scattered throughout Angular do not share a single root. This limits what can be shared across these different component trees. For instance, one cannot share contexts between components if those components are rendered by Angular in separate places.

Example

Let's assume we want to render a new UserStats component in Angular. To render this React component inside Angular:

  1. Create a React component to render and place it in an appropriate location in the src/ directory, e.g. UserStats in src/stats/UserStats/UserStats.tsx

  2. Add UserStats as an export to src/app-index.js, e.g. export { UserStats } from './stats/UserStats/UserStats'

  3. In any Angular template file, use the react-component directive to mount the React component:

    <react-component name="SLApp.UserStats"></react-component>
    <!-- If we need to pass props from the controller (`ctrl`) to the component, we can do that as well -->
    <react-component name="SLApp.UserStats" props="ctrl.props"></react-component>