Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use React Context inside function of Class component

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.

like image 532
Alexander Hörl Avatar asked May 07 '26 11:05

Alexander Hörl


2 Answers

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

like image 187
Jjagwe Dennis Avatar answered May 09 '26 23:05

Jjagwe Dennis


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"> 
like image 38
nick Avatar answered May 10 '26 01:05

nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!