Joey Yi Zhao
Joey Yi Zhao

Reputation: 42418

How to set `contextType` on stateless component

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;

Upvotes: 13

Views: 6896

Answers (2)

kiarash shamaii
kiarash shamaii

Reputation: 26

You must import useContext, then define a variable which fills output of useContext with the argument of your defined context.

import React, {useContext} from 'react';

const MyClass = (props) => {
    const context = useContext(yourContext)
    return <p>{context.name}</p>
}

Upvotes: 0

Eddie Cooro
Eddie Cooro

Reputation: 1958

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>
}

Upvotes: 22

Related Questions