Use contextType to Consume Context in a React Class Without a Consumer

Share this video with your friends

Send Tweet

React 16.6 introduced the ability to consume data from context without using the Consumer component directly. This helps to cut down on unnecessary nesting in your components’ JSX, making them easier to read. In this lesson we’ll see how to replace a Consumer by using the contextType property.

Dave Ceddia
Dave Ceddia(instructor)
~ 6 years ago

FYI: The 'before' code for this lesson is here if you need it.

Jordan.
Jordan.
~ 6 years ago

Hi Dave, How would you go about testing a class component that uses the static contextType field, instead of the render props method.

For instance:

class MyButton extends React.Component {
static contextType = UserContext

  render() {
    const { isConnected } = this.context
    return(
    <button>{isConnected() ? 'Disconnect' : 'Connect'}</button>
    )
  }
}
Jordan.
Jordan.
~ 6 years ago

Currently trying to figure out if something like this would work

   import { render } from 'react-testing-library'
   import MyButton from '../mybutton'

  test('it should change on connect', () => {
    //Set Context like so?
    MyButton.contextType = MockContext
    const { container } = render(<MyButton/>)
  })
Dave Ceddia
Dave Ceddia(instructor)
~ 6 years ago

That seems like it should work. Does it? If not, maybe you could mock the context at the module level: https://jestjs.io/docs/en/es6-class-mocks