I would like to be able to access React Context inside my WebView but the following error occurs:
TypeError: undefined is not an object (evaluating 'Context._context')
Here is my code:
// App.js
import React, { createContext } from 'react'
import { renderToString } from 'react-dom/server'
import { WebView } from 'react-native-webview'
export const AppContext = createContext({
value: '',
setValue: () => { }
})
export default function App() {
const [value, setValue] = useState('Hello there')
return (
<AppContext.Provider value={{ value, setValue }}>
<WebView source={{ html: renderToString(<WebViewComponent />) }} />
</AppContext.Provider>
)
}
// WebViewComponent.js
export default function WebViewComponent() {
const { value, setValue } = useContext(AppContext)
return (
<div>
{value}
</div>
)
}
So a simple solution to the problem is to just pass anything as the props to renderToString(<WebViewComponent />)
instead of using context.
So in my example it will be like this:
// App.js
import React from 'react'
import { renderToString } from 'react-dom/server'
import { WebView } from 'react-native-webview'
export default function App() {
const [value, setValue] = useState('Hello there')
return (
<WebView
source={{
html: renderToString(<WebViewComponent value={value} setValue={setValue} />)
}}
/>
)
}