2

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.