Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  120] [ 5]  / answers: 1 / hits: 22878  / 5 Years ago, sat, february 2, 2019, 12:00:00

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.


More From » reactjs

 Answers
53

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


[#52666] Tuesday, January 29, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sidneyh

Total Points: 118
Total Questions: 108
Total Answers: 105

Location: Mali
Member since Fri, Jun 18, 2021
3 Years ago
sidneyh questions
Tue, Jun 7, 22, 00:00, 2 Years ago
Wed, Apr 13, 22, 00:00, 2 Years ago
Wed, Aug 12, 20, 00:00, 4 Years ago
Wed, Jun 3, 20, 00:00, 4 Years ago
Fri, Apr 24, 20, 00:00, 4 Years ago
;