0

how to useContext in old react component? it show an empty {} when print

import { UserContext } from "../../firebase/user";

export class CreateProduct extends Component {
    static context = UserContext;
    render() {
        console.log(this.context)
    }
}
phongyewtong
  • 5,085
  • 13
  • 56
  • 81
  • 1
    Does this answer your question? [React - useContext inside class](https://stackoverflow.com/questions/61498035/react-usecontext-inside-class) – Tasos Oct 07 '20 at 14:12
  • OP is trying to use Context within a class, not use the hook useContext. – Dan Oct 07 '20 at 14:16

2 Answers2

0

You'll want to rename static context to static contextType. Please refer to the docs:

The contextType property on a class can be assigned a Context object created by React.createContext(). This lets you consume the nearest current value of that Context type using this.context. You can reference this in any of the lifecycle methods including the render function.

Dan
  • 10,282
  • 2
  • 37
  • 64
0

The contextType property on a class can be assigned a Context object created by React.createContext(). This lets you consume the nearest current value of that Context type using this.context. You can reference this in any of the lifecycle methods including the render function.

import { UserContext } from "../../firebase/user";

export class CreateProduct extends Component {
    static contextType = UserContext;
    render() {
        console.log(this.context)
    }
}
knada
  • 336
  • 1
  • 5