i'm trying to use Portal but i get Undefined is not an object error when i wrap my <App/>
with the <PortalProvider>
, basically portal lets u move a component et in the app without having to re-render it again. this is the error that i get in the app but i cant figure out why !!!
ERROR: TypeError : undefined is not an object (evaluation PortalContext>PortalContext>Provider
PortalContext.tsx
import * as React from 'react'
export default PortalContext = React.createContext({
gates: {},
teleport: (gateName: string, element: JSX.Element) => {
return
}
})
PortalProvider.tsx
import * as React from 'react'
import { PortalContext } from './PortalContext'
interface IProps {
children: JSX.Element
}
class PortalProvider extends React.Component<IProps> {
public state = {
gates: {}
}
public render() {
const { children } = this.props
return (
<PortalContext.Provider value={{ gates: this.state.gates, teleport:
this.teleport }}>
{children}
</PortalContext.Provider>
)
}
private teleport = (gateName: string, element: JSX.Element) =>
this.setState({ gates: { ...this.state.gates, [gateName]: element }
})
}
export default PortalProvider
PortalGate.tsx
import * as React from 'react'
import { PortalContext } from './PortalContext'
function PortalGate(props: {
gateName: string
children?: (teleport: (gateName: string, element: JSX.Element) =>
void) => JSX.Element
}) {
const { gateName, children } = props
return (
<PortalContext.Consumer>
{value => {
return (
<React.Fragment>
{value.gates[gateName]}
{children && children(value.teleport)}
</React.Fragment>
)
}}
</PortalContext.Consumer>
)
}
export default PortalGate
app.js
import * as React from 'react'
import PortalProvider from './PortalProvider'
export default class App extends React.Component{
public render() {
return (
<PortalProvider>
<App/>
</PortalProvider>
)
}
}
It's happening because you're default exporting your context and using it with named import.
So, change this line:
import { PortalContext } from './PortalContext'
to:
import PortalContext from './PortalContext'
This this article for reference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.