I have a Card component that needs to trigger a Modal component.
I also have a generic Overlay component that I am using to display some content above my application.
Here is my App component :
class App extends Component {
/* Some Code */
render() {
return (
<div className="c-app">
<Content /> {/* Our content */}
<Overlay /> {/* Our all-purpose-overlay */}
{/* I want my Modal here */}
</div>
)
}
}
I want to use my Overlay component with my Modal component. To get it done, I need both components on the same level (siblings).
And so I did some research on react-portals and I found that I can do the following in my Card component :
class Card extends Component {
constructor() {
super();
this.state = { showModal: false }
}
render() {
const { showModal } = this.state;
return (
{/* Some code */}
{
showModal
&& ReactDOM.createPortal(
<Modal>{* ... *}</Modal>,
document.body
)
}
);
}
}
In the example above, I am sending the Modal into the body element.
Question
How can I get a reference to the App component without sending it through the props?
The thing is that the App component and the Card component are really far apart. It is a little ridiculous to send down the reference of the App component through all the children until it reaches a Card component.
I could also save it it into the Redux Store, but I don't think it is good practice.
How should I fix this? Thanks!