9

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.

2
  • Which version of react are you using? Commented Feb 2, 2019 at 19:12
  • @JjagweDennis 16.6 Commented Feb 2, 2019 at 19:14

2 Answers 2

21

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

Sign up to request clarification or add additional context in comments.

Comments

7

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"> 

1 Comment

Not working as you wrote!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.