Skip to content

Commit 7958381

Browse files
authored
Update life-cycle.mdx - Including an example to use dynamically containers (#121)
This example shows how to update the system observer with the new container. Without this information, an infinite loop is created resulting in the container being inserted in the page multiple times.
1 parent 32b82c2 commit 7958381

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

src/pages/framework/content-scripts-ui/life-cycle.mdx

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ Developers may export a `render` function to override the default renderer. You
263263
- Customize the mounting logic
264264
- Provide a custom `MutationObserver`
265265

266-
For example, to use a custom container:
266+
For example, to use an existing element as a custom container:
267267

268268
```tsx
269269
import type { PlasmoRender } from "plasmo"
@@ -299,6 +299,46 @@ export const render: PlasmoRender = async ({
299299
}
300300
```
301301

302+
How to dynamically create a custom container:
303+
```tsx
304+
import type { PlasmoRender } from "plasmo"
305+
306+
import { CustomContainer } from "~components/custom-container"
307+
308+
const EngageOverlay = () => <span>ENGAGE</span>
309+
310+
// This function overrides the default `createRootContainer`
311+
export const getRootContainer = ({ anchor, mountState }) =>
312+
new Promise((resolve) => {
313+
const checkInterval = setInterval(() => {
314+
let { element, insertPosition } = anchor
315+
if (element) {
316+
const rootContainer = document.createElement("div")
317+
mountState.hostSet.add(rootContainer)
318+
mountState.hostMap.set(rootContainer, anchor)
319+
element.insertAdjacentElement(insertPosition, rootContainer)
320+
clearInterval(checkInterval)
321+
resolve(rootContainer)
322+
}
323+
}, 137)
324+
})
325+
326+
export const render: PlasmoRender = async ({
327+
anchor, // the observed anchor, OR document.body.
328+
createRootContainer // This creates the default root container
329+
}) => {
330+
const rootContainer = await createRootContainer(anchor)
331+
332+
const root = createRoot(rootContainer) // Any root
333+
root.render(
334+
<CustomContainer>
335+
<EngageOverlay />
336+
</CustomContainer>
337+
)
338+
}
339+
```
340+
341+
302342
To utilize the built-in `Inline Container` or `Overlay Container`:
303343

304344
```tsx

0 commit comments

Comments
 (0)