I'm working in a ReactJS project that needs to use the Google Maps. I've looked into the plugins available on NPM, but none of them fits all my needs, so I'm using the pure JavaScript API for Google-Maps.
Following the Info Windows documentation from Google-Maps to create the info-windows, I'm trying to do this way:
data.pieces.map(piece => {
let pieceInfo =
`<div class="infowindow">
<h1>${piece.Name}</h1>
<p>${piece.Description}</p>
<p>${piece.RandomText}</p>
</div>`
let infowindow = new window.google.maps.InfoWindow({
content: pieceInfo
})
})
This approach, however, doesn't handle all the use cases that I have. Since i'm working with ReactJS, I would like to know if is possible to use the JSX - and all its resources - as the InfoWindow content. My other attempt was the following:
attempt = (content) => (
<div className="infowindow">
<h1>{content.Name}</h1>
<p>{content.Description}</p>
</div>
)
...
data.pieces.map(piece => {
let test = this.attempt(piece)
let infowindow = new window.google.maps.InfoWindow({
content: test,
})
})
This, unfortunately, doesn't work too, and throws this error in the console:
InvalidValueError: setContent: not a string; and [object Object]
So, I don't know how to proceed. It's possible to use JSX as the content for Info window?
Thanks in advance.
Since it expects you to pass a string in, you'll have to render the JSX to a string. Only way i know to do that is using react-dom/server (despite the package name, this function can work client side too):
import ReactDOMServer from 'react-dom/server';
// ...
data.pieces.map(piece => {
let content = ReactDOMServer.renderToString(
<div className="infowindow">
<h1>{piece.Name}</h1>
<p>{piece.Description}</p>
</div>
);
let infowindow = new window.google.maps.InfoWindow({ content });
});
See more info here: https://reactjs.org/docs/react-dom-server.html#rendertostring