Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Correct way of passing a reference to a react-portal

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!

like image 351
Bird Avatar asked Nov 07 '22 03:11

Bird


1 Answers

Redux offers functionality for passing refs without saving them explicitly in the store.

You can set the withRef option as true in your connect() call:

connect(null, null, null, { withRef: true })(<Your component>);

And access the ref by the following method:

ref={connectedComponent =>
        this.<Your component>=
        connectedComponent.getWrappedInstance();

This medium article may prove helpful. https://itnext.io/advanced-react-redux-techniques-how-to-use-refs-on-connected-components-e27b55c06e34 Also were I got the sample code above from.

like image 90
Rowan Baker-French Avatar answered Nov 14 '22 22:11

Rowan Baker-French