ronitgupta
ronitgupta

Reputation: 33

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

Upvotes: 2

Views: 913

Answers (2)

Nadia Chibrikova
Nadia Chibrikova

Reputation: 5036

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

Upvotes: 1

shiponcs
shiponcs

Reputation: 1687

You're using Test1 component which consumes Test0, a context, that you suppose to provide values, but in Test0 you're providing no value. You wrongly implemented the provider in separate Component, Test2, that you don't render so Test0 doesn't know about the provided values and it's assuming you didn't define the context.

Upvotes: 0

Related Questions