Using React Portals for cleaner components
In this article I want to share a simple technique using React Portals for better decoupling of context specific features that live on global contexts.
If that was a mouthful, a quick example will make it clearer.
Lets say we have an application where the header can have a contextual menu, some buttons, links and other things that depend on the page that the user is visiting. Our app structure could look like this:Where the AppHeader component is in charge of rendering all of these things:
If some of these components have to be rendered conditionally, then we’ll have to put all of that presentation logic in the AppHeader component and the corresponding state that controls that logic on a parent component, like the App component, so it can be accessed from anywhere in the application.
And in the App component:
So now we face an scenario where we’ll have to pass some of this state and callbacks to our routed components as props. We’ll also have to set and unset some of these properties when entering and leaving the page:
We would have to do something similar in every page where we want to change the options, enable a button or do anything related to the content of the header, which is going to get harder to maintain as the application grows and more pages are added.
There’s also another problem and it’s related to the handlers that we’re passing to our buttons, for example handleDoSomething. If handleDoSomething changes any state that is relevant to one of our pages, we would have to keep that state in the App component.
0 Comments