I am using the React
context new API as below code. The last line will register the context into my component. I wonder how I can use the contextType
for stateless component?
class MyClass extends React.Component {
render() {
let value = this.context;
/* render something based on the value of MyContext */
}
}
MyClass.contextType = MyContext;
I tried below code but it doesn't seem to work. The context
in the component is empty object.
const MyClass = (props, context) => {
...
}
MyClass.contextType = MyContext;
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.
Stateful and Stateless Components In React, a stateful component is a component that holds some state. Stateless components, by contrast, have no state. Note that both types of components can use props. In the example, there are two React components.
Notice the stateless component is written as a function. As cool as state is, you should always aim to make your components as simple and stateless as possible, so different components can be reused like Lego pieces, even if you don't have immediate plans to reuse a component.
There is no way of doing it with contextType.
You should use contextConsumer with renderProps pattern or React's useContext hook (introduced in React 16.8)
The first one will look like this:
const MyClass = (props) => {
return (
<myContext.Consumer>
{({name}) => <View>{name}</View>}
</myContext.Consumer>
)
}
And the second (preferred) way of doing it looks like this:
import React, {useContext} from 'react';
const MyClass = (props) => {
const {name} = useContext(myContext)
return <View>{name}</View>
}
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