score:0

This is how it can be achieved.

 class BasElement extends React.Component {
  componentDidMount() {
    console.log(this.props.context);
  }

  render() {
    return null;
  }
}

const Element = () => (
  <Context.Consumer>
    {context =>
      <BaseMapElement context={context} />
    }
  </Context.Consumer>
)

score:0

For the @wertzguy solution to work, you need to be sure that your store is defined like this:

// store.js
import React from 'react';

let user = {};
const UserContext = React.createContext({
  user,
  setUser: () => null
});

export { UserContext };

Then you can do

import { UserContext } from 'store';

console.log(UserContext._currentValue.user);

score:1

You can via an unsupported getter:

YourContext._currentValue

Note that it only works during render, not in an async function or other lifecycle events.

score:7

You can achieve this in functional components by with useContext Hook.

You just need to import the Context from the file you initialised it in. In this case, DBContext.

 const contextValue = useContext(DBContext);

score:31

Update

As of React v16.6.0, you can use the context API like:

class App extends React.Component {
    componentDidMount() {
       console.log(this.context);
    }
    render() {
       // render part here
       // use context with this.context
    }
}
App.contextType = CustomContext

However, the component can only access a single context. In order to use multiple context values, use the render prop pattern. More about Class.contextType.

If you are using the experimental public class fields syntax, you can use a static class field to initialize your contextType:

class MyClass extends React.Component {
  static contextType = MyContext;
  render() {
    let value = this.context;
    /* render something based on the value */
  }
}

Render Prop Pattern

When what I understand from the question, to use context inside your component but outside of the render, create a HOC to wrap the component:

const WithContext = (Component) => {
  return (props) => (
      <CustomContext.Consumer>
           {value =>  <Component {...props} value={value} />}
      </CustomContext.Consumer>
  )
}

and then use it:

class App extends React.Component {
    componentDidMount() {
       console.log(this.props.value);
    }
    render() {
       // render part here
    }
}
export default WithContext(App);

Related Query

More Query from same tag