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?
The simple way to access the context values is by wrapping the child component in the Consumer for Class component and for the functional component we can access context with the help of useContext method of React. From there, we can access the context value as props.
Consuming Context With Class-based ComponentsOne is to use the context from Consumer like “ThemeContext. Consumer” and the other method is by assigning context object from current Context to contextType property of our class. There is always a difference in how we want to use the Context.
To access a React context outside of the render function, we can use the useContext hook. We create the UserContext by calling the React. createContext method with a default context value. Then in the Users component, we call the useContext hook with UserContext to accxess the current value of UserContext .
If you're only using Redux to avoid passing down props, you can replace it with Context API. Context is great for sharing trivial pieces of state between components. Redux is much more powerful and provides a set of handy features that Context doesn't have.
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;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With