How to add a button in infowindow with google-maps-react?

The way how InfoWindow component is implemented in google-maps-react library does not support to attach event handlers to info window dynamic content. The similar issue has been discussed in this thread.

The solution would be render InfoWindow children into a DOM node in order to prevent losing the React context, the following component could be introduced for that matter:

export default class InfoWindowEx extends Component {
  constructor(props) {
    super(props);
    this.infoWindowRef = React.createRef();
    this.contentElement = document.createElement(`div`);
  }

  componentDidUpdate(prevProps) {
    if (this.props.children !== prevProps.children) {
      ReactDOM.render(
        React.Children.only(this.props.children),
        this.contentElement
      );
      this.infoWindowRef.current.infowindow.setContent(this.contentElement);
    }
  }

  render() {
    return <InfoWindow ref={this.infoWindowRef} {...this.props} />;
  }
}

Now once InfoWindow replaced with InfoWindowEx event handlers could be attached to Component children:

<InfoWindowEx
        marker={this.state.activeMarker}
        visible={this.state.showingInfoWindow}>
        <button type="button" onClick={this.showDetails}>
            Show details
        </button>
</InfoWindowEx>

Demo

Tags:

Reactjs