Using React in Angular Applications
Two scenarios call for the use of React in an Angular application. First, there is a component in the React ecosystem that will take us weeks to develop, for example, a Timeline component. Second, we may have acquired a company that uses React and need to integrate it into our existing application.
In this article, I will show how to integrate React in both cases. Let’s start with the most simple case where we must use a React component.
Render a React Component
Let’s create a directive that takes a React component and props and renders it into the host. The article assumes you are familiar with React.
The directive is straightforward. It takes a React component and props, creates a root, and rerenders it whenever it changes.
For our example, we’ll render the React Select component inside a lazy todos page component. We’ll install it by using npm i react-select
and pass it to our directive:
Note that the React code will only be loaded when we navigate this page because our todo component is lazily loaded.
We can go one step further and load the entire React chunks on demand. We’ll adjust the directive as follows:
Our code has been changed to use the import function instead of eager imports. Now we can use it in our todos page component:
Render a React Application
The process of rendering an application is almost identical to rendering a component with a single short add-on. We aim to expose Angular’s application injector
to the rendered React application so we can use Angular services within it. To do so, we’ll use React Context, which exposes the injector
and render the React application inside it:
ng-react.ts
We’ve created a Context
that provides an Angular injector and useInjector
hook. Next, we’ll implement a service that renders a React component:
ng-react.ts
The render()
method renders the provided React component under the NgContext
provider so that it can access the Angular injector
we provide.
I have created a React application using Nx that uses our useInjector
function:
We navigate to our home page whenever we click the home button using the Angular router
we obtain from the injector
.
Let’s render it in our todos page component:
Follow me on Medium or Twitter to read more about Angular and JS!