18

I'm newbie in react and i want use useContext inside my class, how do i solve this? This is example of my current code right now

import { Context } from '../context/ChatListContext'

const ChatList = ({ onAction }) => {
    const {state, fetchChatList} = useContext(Context)

And i'm expecting the same for my class

import { Context } from '../context/ChatListContext'

class MainScreen extends Component {

//const {state, fetchChatList} = useContext(Context) *how do i declare this?

  constructor(props) {
    super(props)
    this.state = { loading: true, showAction: false }
    setTimeout(() => {
      StatusBar.setBackgroundColor(primary)
    }, 100)
  }
...
}

Can anyone enlighten me?

Hanif Nr
  • 432
  • 1
  • 5
  • 15

3 Answers3

47

useContext is a hook that can't be used in a class component. For a class component you define a static contextType

import { Context } from '../context/ChatListContext'

class MainScreen extends Component {

 static contextType = Context

  constructor(props) {
    super(props)
    this.state = { loading: true, showAction: false }
    setTimeout(() => {
      StatusBar.setBackgroundColor(primary)
    }, 100)
  }
...
  render() {
       const {state, fetchChatList} =this.context;
  }
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
5

The contextType property on a class can be assigned a Context object created by React.createContext().

Take note of how outside the class we can assign the value of MyContext to the Class.contextType

You can then access all of your contexts with this.context

import MyContext from '@/context/MyContext'

class Login extends React.component() {

  constructor(props) {
    super(props);

    this.state = { four: 2*2 }
  }

  render() {

    console.log(this.context);
    
    return (
      <div>

      </div>
    )
  }

}

Login.contextType = MyContext
dylzee
  • 373
  • 3
  • 8
0

Just to suggest more flexible solution for this issue

Create Wrapper component with your context:

import { useContext } from "react";
import { Context } from '../context/ChatListContext'

export const withContext = (Component) => {
  const Wrapper = (props) => {
    const context = useContext(Context);

    return <Component context={context} {...props} />;
  };

  return Wrapper;
};

Then wrap your class in it:

export default withContext(MainScreen);

Now within this class you can access your values with:

this.props.context

You can use this approach to consume multiple contexts:

const contextOne = useContext(SomeContext);
const contextTwo = useContext(SomeOtherContext);
    
return <Component contextOne={contextOne} contextTwo={contextTwo} {...props} />;
Mitchy
  • 85
  • 1
  • 7