File size: 2,332 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
---
title: Environment Provider
description: Used to render components in iframes, Shadow DOM, or Electron.
links:
  storybook: components-environment-provider--basic
  recipe: environment-provider
  ark: https://ark-ui.com/docs/utilities/environment
---

We use
[Zag.js](https://zagjs.com/overview/composition#custom-window-environment)
internally, which relies on DOM query methods like `document.querySelectorAll`
and `document.getElementById`. In custom environments like iframes, Shadow DOM,
or Electron, these methods might not work as expected.

To handle this, Ark UI includes the `EnvironmentProvider`, allowing you to set
the appropriate root node or document, ensuring correct DOM queries.

## Usage

```jsx
import { EnvironmentProvider } from "@chakra-ui/react"
```

```jsx
<EnvironmentProvider>{/* Your App */}</EnvironmentProvider>
```

## Examples

### iframe

Here's an example that uses `react-frame-component` to set the
`EnvironmentProvider`'s value with the iframe environment.

```jsx
import { EnvironmentProvider } from "@chakra-ui/react"
import Frame, { FrameContextConsumer } from "react-frame-component"

export const Demo = () => (
  <Frame>
    <FrameContextConsumer>
      {({ document }) => (
        <EnvironmentProvider value={() => document}>
          {/* Your App */}
        </EnvironmentProvider>
      )}
    </FrameContextConsumer>
  </Frame>
)
```

### Shadow DOM

Here's an example that uses `react-shadow` to set the `EnvironmentProvider`'s
value with Shadow DOM environment.

```jsx
import { EnvironmentProvider } from "@chakra-ui/react"
import { useRef } from "react"
import root from "react-shadow"

export const Demo = () => {
  const portalRef = useRef()
  return (
    <root.div ref={portalRef}>
      <EnvironmentProvider
        value={() => portalRef?.current?.shadowRoot ?? document}
      >
        {/* Your App */}
      </EnvironmentProvider>
    </root.div>
  )
}
```

### Accessing Context

Use the `useEnvironmentContext` hook to access the `RootNode`, `Document`, and
`Window` context.

```jsx
import { useEnvironmentContext } from "@chakra-ui/react"

export const Demo = () => {
  const { getRootNode } = useEnvironmentContext()

  return <pre>{JSON.stringify(getRootNode(), null, 2)}</pre>
}
```

## Props

<PropTable component="Environment" part="EnvironmentProvider" />