Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set `contextType` on stateless component

Tags:

reactjs

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;
like image 684
Joey Yi Zhao Avatar asked Feb 16 '19 08:02

Joey Yi Zhao


People also ask

Can I use useContext in class component?

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.

How is stateless component different from a stateful component?

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.

Should React components be stateless?

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.


1 Answers

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>
}
like image 74
Eddie Cooro Avatar answered Sep 20 '22 20:09

Eddie Cooro