How do you use contextType?
ContextType is used to consume the context object. The contextType property can be used in two ways,
-
contextType as property of class: The contextType property on a class can be assigned a Context object created by React.createContext(). After that, you can consume the nearest current value of that Context type using this.context in any of the lifecycle methods and render function.
Lets assign contextType property on MyClass as below,
class MyClass extends React.Component {componentDidMount() {let value = this.context;/* perform a side-effect at mount using the value of MyContext */}componentDidUpdate() {let value = this.context;/* ... */}componentWillUnmount() {let value = this.context;/* ... */}render() {let value = this.context;/* render something based on the value of MyContext */}}MyClass.contextType = MyContext; -
Static field You can use a static class field to initialize your contextType using public class field syntax.
class MyClass extends React.Component {static contextType = MyContext;render() {let value = this.context;/* render something based on the value */}}
April 30, 2022
289
Read more
What is React?
November 06, 2022
ReactJSHow to programmatically trigger click event in React?
November 06, 2022
ReactJS