0

In my REACT application, I'm trying to render a Component programmatically, but pasing to it any REACT context. Let me show you a simple example with this sandbox: https://codesandbox.io/s/kind-carson-u0hup?file=/src/App.tsx

As you can see, what I want to do is rendering <Dialog> programmatically when I click a button. But, inside that <Dialog>, I want to use any context created on the React Tree.
Unfortunately, I am aware that React.render does not pass any context, thus this cannot work: if you click on the button, you will see that, while the context in <InnerComponent> provides the value 'FooBar'. inside <Dialog> I have the default value 'initialValue'.

Thus, the question is, is there any way I can programmatically render a component, AND passing to its any kind of context?
I'm aware that React.createPortal does pass the context, but that method MUST be called inside the return statement of a component, while instead, in my case, I render the <Dialog> after a click on the Button.
Also, yes, I could always have the <Dialog> rendered, and use a prop isVisible.. But this is a simpler example.

I've read several things (some of these in the following links), but none of these really helped me:

Jolly
  • 1,678
  • 2
  • 18
  • 37

1 Answers1

0

You can not put the render of component outside of your ContextProvider.

Check this link: https://codesandbox.io/s/busy-curran-pbz6p?file=/src/App.tsx:0-834

davood Sandoghsaz
  • 674
  • 1
  • 4
  • 13
  • Thanks for the effort, but I literally wrote that I'm looking for a solution (if it exists) to render from outside the render.. And not a solution that includes having the `` in the return with some `isVisible` prop – Jolly Dec 02 '21 at 14:34
  • React allows all child components to access the `ContextConsumer` but in your way the `` component won't recognize as a child component – davood Sandoghsaz Dec 02 '21 at 14:38