How can I access objects inside of React Context inside a function of a Class Component.
I've got the following React Component
import StoreContext from '../../context/StoreContext'
class ProductForm extends Component {
static contextType = StoreContext
constructor(props) {
super(props);
}
handleOptionChange(event) {
const test = this.contextType.client.testObject
}
I've tried accessing the client object inside the context like this but It doesn't work because it says cant read the property of undefined.
I'm wondering where my mistake is.
Change this to context instead of contextType
this.context.client.testObject
i.e Your code should look like
import StoreContext from '../../context/StoreContext'
class ProductForm extends Component {
static contextType = StoreContext
constructor(props) {
super(props);
}
handleOptionChange(event) {
const test = this.context.client.testObject
}
Leave the static propery as context type and access context in methods as using this.context
I would describe using context in a class component in 3 steps
define the context object with a value you want to share with entire app
const StaticBackEditor = React.createContext({isDebug: true})
wrap the entire app this context and set the values
function App() {
return (
<Provider store={store}>
<StaticBackEditor.Provider value={{isDebug: true}}>
<div className="App">
<Layout />
</div>
</StaticBackEditor.Provider>
</Provider>
)
use the value in a component
class Tree extends React.Component<IProps, IState> {
// this must be named contextType!
static contextType = StaticBackEditor
}
// its wired that we need to access a static field through this , but you do!
{this.context.isDebug && <span className="debug">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With