0

I am rendering my react component inside an existing JSP page using

ReactDOM.render(
      React.createElement(MyReactComponents.myReactComponent, {
        props
      }),
  document.querySelector("#id")
);

and the react component is as follows:

import MyStore from "./MyStore";
const MyReactComponent: React.FC<any> = (props: any) => {
      const store = useContext(MyStore);
      store.myFunction();
      ---code---
}

and MyStore is as follows:

export class MyStore{
      ---Code---
}
export default createContext(new MyStore());

But i'm getting this error: enter image description here

And one more importing thing to notice is that when I'm trying to render this react component on top of another existing react component, i'm not getting any error and everything is working fine.

Can someone please explain me what might be causing the issue?

1 Answers1

0

I'm not sure, but maybe you are misusing the useContext hook?

Whenever you use it inside a component Child, then at least one of its parent component must call the <Context>.Provider, so that it is initialized down the tree.

In your example, you render MyReactComponent using ReactDOM.render: due this, I suppose MyReactComponent is the first component in your tree. If that is the case, when you use useContext inside it, it cannot find any MyStore context.

So, probably, you just need to wrap your MyReactComponent with a context provider.

export class MyStore { ... }
export const MyStoreContext = createContext(new MyStore());

---

ReactDOM.render(
    <MyStoreContext.Provider>
        <MyReactComponent {...props />
    </MyStoreContext.Provider>
, document.querySelector("#id"));

And then, inside MyReactComponent, you can use const store = useContext(MyStoreContext);.

Jolly
  • 1,678
  • 2
  • 18
  • 37