DEV Community

Cover image for Introducing ngx-react : 🅰️Angular  + ⚛️React interoperability without pain.
Olivier Guimbal
Olivier Guimbal

Posted on

Introducing ngx-react : 🅰️Angular + ⚛️React interoperability without pain.

Have you ever wanted to use React components in an Angular application ? Or to start migrating an Angular app to React component-by-component ? Or simply use both at the same time ?

I developped ngx-react which allows you to do just that with ease.

It enables you to use your Angular components in React, and vice versa, quite transparently, and without boilerplate.

📐 Setup

Just declare a bridge, somewhere in your application:

import { NgxReactBridge } from 'ngx-react';

export const bridge = new NgxReactBridge()
    // bridge options:
    .addProvider(/** Add a global react provider here */);
Enter fullscreen mode Exit fullscreen mode

Use 🅰️ in ⚛️

Then, to use an Angular component in React, just import it like that:

const AsReact = bridge.toReact(MyAngularCommonent);

// use it 👉  <AsReact prop={whatever} />
Enter fullscreen mode Exit fullscreen mode

The generated ⚛️ component will take as props all the @Input()s of your 🅰️ component, and all the @Output()s, mapped to functions. (i.e. @Output() onThing: EventEmitter<string> will be mapped to prop onThing: (event: string) => void.

Use ⚛️ in 🅰️

To use a React component in Angular, you'll have to do a tiny bit more work... for instance if you have a React component:

function MyReactComponent(props: {
  data: string;
  dataChange: (evt: string) => void;
}) {
    // [...]
}

Enter fullscreen mode Exit fullscreen mode

Then magically convert it to its Angular counterpart like that:

@Directive({ selector: "my-react-component" })
export class MyReactComponent_Angular extends reactBridge.toAngular(
  MyReactComponent
) {

  // a bit of extra work: You will have to map the properties yourself 
  @Input()
  data!: string;
  @Output()
  dataChange = new EventEmitter();
}
Enter fullscreen mode Exit fullscreen mode

(the Angular compiler doesnt allow to build dynamic components... so we have to declare them statically)

Services

Just inject Angular services in React like that:

const service = useService(MyAngularService);
Enter fullscreen mode Exit fullscreen mode

Wrapping up

I'll write more about this when I have more time 👉 But please share your thought if you have some :)

More details on the ngx-react repository

Discussion (2)

Collapse
alaindet profile image
Alain D'Ettorre

Some people just want to watch the world burn

Collapse
shilovp profile image
Pavel Shilov

Custom html components written in Stencil, I choose you !