To use JSX as content for an InfoWindow in Google Maps API use the following steps :
Render JSX to HTML: JSX content needs to be rendered to an HTML string or element for the InfoWindow because Google Maps API expects HTML, not JSX.
Render JSX using React: ReactDOM.render() allows you to render JSX to a DOM element. You then set that as the content for your InfoWindow.
Code:
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
useEffect(() => {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: { lat: -34.397, lng: 150.644 },
});
const infoWindow = new google.maps.InfoWindow();
// JSX content for the InfoWindow
const content = (
<div>
<h1>InfoWindow Title</h1>
<p>This is an InfoWindow created using JSX!</p>
</div>
);
// Create a div element to render the JSX into
const div = document.createElement("div");
// Render the JSX into the div element
ReactDOM.render(content, div);
// Set the rendered content as the InfoWindow's content
infoWindow.setContent(div);
const marker = new google.maps.Marker({
position: { lat: -34.397, lng: 150.644 },
map: map,
});
marker.addListener("click", () => {
infoWindow.open(map, marker);
});
}, []);
return <div id="map" style={{ height: "500px" }} />;
}
export default App;