React context return undefined

You need to provide a context default value in createContext()

Like

export const UserContext = React.createContext('default');

Or

export const UserContext = React.createContext({ctx_key:"ctx_value"});

Also, make sure to pass context in the constructor if you override it!

    export default class Profile extends React.Component {
        static contextType = AuthContext;
        // make sure you pass the context along to super!
        constructor(props, context) {
            super(props, context);
            ...
        }
    }

In the child component change context to value (function parameter) in the Consumer section as thats is the prop passed to the Provider

<UserContext.Consumer>
  {(value) => ( 
    <p>im inside the consumer {console.log(value)}</p>
  )}
</UserContext.Consumer>

Full working sample

    import React, { Component } from 'react'
    const UserContext = React.createContext()

    const Main = () => (
      <Parent>
        <Child/>
      </Parent>
    )

    export default Main

    //***************************************/

    class Parent extends Component {

      state = {
        editGroup: false
      }

      render() {
        return (
          <UserContext.Provider value={{
            state: this.state
          }}>
            {this.props.children}
          </UserContext.Provider>
        )
      }
    }

    //***************************************/

    const Child = () => {
      return (
        <React.Fragment>
          <UserContext.Consumer>
            {(value) => (
              <p>Inside consumer {console.log(value)}</p>
            )}
          </UserContext.Consumer>
        </React.Fragment>
      );
    }

    //***************************************/

Output: state: {editGroup: false}

Tags:

Reactjs