Skip to content

Commit

Permalink
Add React Strict Mode support (bitovi#169)
Browse files Browse the repository at this point in the history
  • Loading branch information
chez14 committed Jan 30, 2024
1 parent 002a007 commit 3ce1656
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
11 changes: 8 additions & 3 deletions packages/core/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@ type PropNames<Props> = Array<PropName<Props>>

export interface R2WCOptions<Props> {
shadow?: "open" | "closed"
props?: PropNames<Props> | Partial<Record<PropName<Props>, R2WCType>>
props?: PropNames<Props> | Partial<Record<PropName<Props>, R2WCType>>,
strictMode?: boolean
}

export interface R2WCRenderer<Props, Context> {
mount: (
container: HTMLElement,
ReactComponent: React.ComponentType<Props>,
props: Props,
strictMode: boolean
) => Context
update: (context: Context, props: Props) => void
update: (context: Context, props: Props, strictMode: boolean) => void
unmount: (context: Context) => void
}

Expand Down Expand Up @@ -136,14 +138,17 @@ export default function r2wc<Props extends R2WCBaseProps, Context>(
[renderSymbol]() {
if (!this[connectedSymbol]) return

const strictMode = options.strictMode || false;

if (!this[contextSymbol]) {
this[contextSymbol] = renderer.mount(
this.container,
ReactComponent,
this[propsSymbol],
strictMode
)
} else {
renderer.update(this[contextSymbol], this[propsSymbol])
renderer.update(this[contextSymbol], this[propsSymbol], strictMode)
}
}
}
Expand Down
12 changes: 10 additions & 2 deletions packages/react-to-web-component/src/react-to-web-component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,14 @@ function mount<Props extends object>(
container: HTMLElement,
ReactComponent: React.ComponentType<Props>,
props: Props,
strictMode: boolean
): Context<Props> {
const root = createRoot(container)

const element = React.createElement(ReactComponent, props)
let element: React.ReactElement = React.createElement(ReactComponent, props)
if (strictMode) {
element = React.createElement(React.StrictMode, null, element)
}
root.render(element)

return {
Expand All @@ -30,8 +34,12 @@ function mount<Props extends object>(
function update<Props extends object>(
{ root, ReactComponent }: Context<Props>,
props: Props,
strictMode: boolean
): void {
const element = React.createElement(ReactComponent, props)
let element: React.ReactElement = React.createElement(ReactComponent, props)
if (strictMode) {
element = React.createElement(React.StrictMode, null, element)
}
root.render(element)
}

Expand Down

0 comments on commit 3ce1656

Please sign in to comment.