Pass A react component to leaflet popup

Viewed 2513

I am using leaflet in my react code and I am not using react-leaflet. I want to pass a react component or jsx code to binbPopup function to every tooltip.

let marker = new L.marker(...).bindPopup(<div>Hi</div>)

bindPopup gets string as a input so I cannot use jsx. I also tried to use react portals but still it doesn't work. What is the solution for this problem?

1 Answers

You can use renderToString method of ReactDOMServer to convert React component to markup string.

import React, { Component } from "react";
import ReactDOM from "react-dom";
import ReactDOMServer from "react-dom/server";
import * as L from "leaflet";
import "./styles.css";

const CustomReactPopup = () => {
  return (
    <div style={{ fontSize: "24px", color: "black" }}>
      <p>A pretty React Popup</p>
    </div>
  );
};

class App extends Component {

  componentDidMount() {
    var map = L.map("map").setView([51.505, -0.09], 13);
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution:
        '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    L.marker([51.5, -0.09])
      .addTo(map)
      .bindPopup(ReactDOMServer.renderToString(<CustomReactPopup />))
      .openPopup();
  }

  render() {
    return (
      <div>
        <div id="map" />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);  

Working example here: https://codesandbox.io/s/leaflet-with-react-znk11

Related