0

Why Context value showing undefined?

src/Context.js:

import React, { Component } from 'react';

const Context = React.createContext();

export class Provider extends Component {
  state = { a: 1, b: 2 };
  render() {
    return (
      <Context.Provider value={this.state}>
        {this.props.children}
      </Context.Provider>
    );
  }
}
export const Consumer = Context.Consumer;

src/country/CountryList.js:

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

class CountryList extends Component {
  render() {
    return (
      <Consumer>
        {value => {
          console.log('val:' + value);
        }}
      </Consumer>
    );
  }
}
export default CountryList;

Trying to pass context value in CountryList but it's showing undefined, can't figure out why. Thanks in Advance

1 Answer 1

2

You need to wrap your CountryList component with Provider i.e you need to import Provider.

import React, { Component } from 'react';
import { Provider,Consumer } from '../../Context';

class CountryList extends Component {
  render() {
    return (
      <Provider>
        <Consumer>
          {value => {
            console.log('val:' + value);
          }}
        </Consumer>
     </Provider>
    );
  }
}
export default CountryList;

Stackblitz example here : https://stackblitz.com/edit/react-143zwt (I just added for testing. It will give you idea. I do not add this code there.)

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

2 Comments

Thanks a lot, it's working. You may attach any documentation reference so its more helpful for others.
I added stackblitz url just for your reference. You can check there. Your console log is working fine.

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.