Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { IAugmentedJQuery, IComponentOptions } from 'angular'
import fromPairs = require('lodash.frompairs')
import NgComponent from 'ngcomponent'
import * as React from 'react'
import { render, unmountComponentAtNode } from 'react-dom'
import { flushSync } from 'react-dom'
import { createRoot, Root } from 'react-dom/client'

/**
* Wraps a React component in Angular. Returns a new Angular component.
Expand All @@ -15,7 +16,7 @@ import { render, unmountComponentAtNode } from 'react-dom'
* const AngularComponent = react2angular(ReactComponent, ['foo'])
* ```
*/
export function react2angular<Props>(
export function react2angular<Props extends { [k: string]: any }>(
Class: React.ComponentType<Props>,
bindingNames: (keyof Props)[] | null = null,
injectNames: string[] = []
Expand All @@ -25,12 +26,13 @@ export function react2angular<Props>(
|| []

return {
bindings: fromPairs(names.map(_ => [_, '<'])),
bindings: fromPairs(names.map((_: any) => [_, '<'])),
controller: ['$element', ...injectNames, class extends NgComponent<Props> {
static get $$ngIsClass() {
return true
}
isDestroyed = false
root: Root | null = null
injectedProps: { [name: string]: any }
constructor(private $element: IAugmentedJQuery, ...injectedProps: any[]) {
super()
Expand All @@ -41,15 +43,22 @@ export function react2angular<Props>(
}
render() {
if (!this.isDestroyed) {
render(
<Class {...this.props} {...this.injectedProps as any} />,
this.$element[0]
)
if (!this.root) {
this.root = createRoot(this.$element[0])
}
flushSync(() => {
this.root!.render(
<Class {...this.props} {...this.injectedProps as any} />
)
})
}
}
componentWillUnmount() {
this.isDestroyed = true
unmountComponentAtNode(this.$element[0])
if (this.root) {
this.root.unmount()
this.root = null
}
}
}]
}
Expand Down
Loading