2

when i use context in Reactjs ,by using hooks I just can use 'useContext' for function component in other module , but I want to use it for --> class component <-- in other module but i cant do it, and in browser console i see this error: ==>> ((

ReferenceError: Cannot access 'MyContext' before initialization
Module.MyContext
http://localhost:3000/static/js/main.chunk.js:12:101
Module../src/news.js
F:/0 React Js project/my-appfirst-app/src/news.js:21

))

do we have any way to use class component in other module?

these are my codes

parent commponent:

import React,{createContext,Component} from 'react';
import ReactDOM from 'react-dom';
import Roots from './news'
import * as serviceWorker from './serviceWorker';


export let MyContext=createContext();

class Show extends Component{
  render(){
    return(
      <MyContext.Provider value={{name:'ali',family:'mohammady',done:'false'}} >
        <div className='container-main'>
          <Roots />
        </div>
      </MyContext.Provider>
    )
  }
}

ReactDOM.render(<Show />, document.getElementById('root'));

and this child module:

import React,{Component} from 'react';
import {MyContext} from './index'

class Roots extends Component{
  static  contextType = MyContext;
  render(){
    return(
      <>
        <p>{console.log(this.context)}</p>
      </>
    )
  }
}

export default Roots;

I wonder how to work this codes if i put child component in parent component !!??

2 Answers 2

3

You need to export then import the consumer from the context to use it like that

export let MyContext=createContext();
export const MyContextConsumer = MyContext.Consumer

Then import that consumer and use it

import React,{ Component } from 'react';
import { MyContextConsumer } from './index'

class Roots extends Component{
  render(){
    return(
      <MyContextConsumer>
        {value => <p>{console.log(value)}</p>}
      </MyContextConsumer>
    )
  }
}

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

Comments

1

@topched

thanks for your help your answer is very helpful for me but the console show the error again and then I did a few changes on your code and it runs without error.

when I use bottom script in index.js , i get error but i created a new file with the name context.js and put bottom script in it , the codes run without error

export let MyContext=createContext();
export const MyContextConsumer = MyContext.Consumer

1 Comment

I dont quite follow what you are saying but it sounds like its working so thats great

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.