Search code examples
javascriptreactjsreact-context

React App is giving error when using context API


I am learning React and right now trying to implement the old way of working with Context API but when I try to compile I get an error.

It says :

TypeError: context is undefined. Version is 17.0.1

Here are the files I use:

Test0.js

import React from 'react';
const Test0 = React.createContext();
export default Test0;

Test1.js

import React, { Component } from 'react';
import Test0 from './Test0';

class Test1 extends Component{
render(){
    return (
            <Test0.Consumer>
                {context => (<p>This is {context.name}</p> )}
            </Test0.Consumer>
        );
}
}
export default Test1;

Test2.js

import React, { Component } from 'react';
import Test0 from './Test0';
import Test1 from './Test1';

class Test2 extends Component{
state = {
    name: 'James',
    age : 30
}
render(){
    return (
        <Test0.Provider
            value={{
                name : this.state.name,
                age: this.state.age
            }}
        >
            <Test1 />
        </Test0.Provider>
        );
}
}

export default Test2;

I then render <Test1 /> in app.js


Solution

  • I then render < Test1 /> in app.js

    You need to render Test2 because you define your Context Provider there. Below is the link for the full working code.

    CODESANDBOX LINK: https://codesandbox.io/s/context-api-issue-lqkv8