Rendering react components inside popup of react-leaflet-draw drawn layer on react-leaflet

Ricardo Oliveira picture Ricardo Oliveira · Mar 20, 2017 · Viewed 7.1k times · Source

I'm trying to render some react components inside a layer created by react-leaflet-draw.

This is my attempt:

_onCreate(e) {
        var layer = e.layer
        layer.bindPopup(
            <Content>
                <Label>Flower Name</Label>
                <Input type="text" placeholder="Flower Name"/>
                <Label>Flower Index</Label>
                <Input type="number" placeholder="Flower Index"/>
                <Label>Flower Radius</Label>
                <Input type="number" placeholder="Flower Radius"/>
                <Button color="isSuccess" >Add Flower</Button>
            </Content>
        )
    }

The components are supplied by react-bulma.

But I try this approach I get the following error: Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

If I make the content a simple string I get plain HTML fields and a button but no access to external functions nor the actual Bulma components.

Essentially I want to be able to save the new shape on the database.

From a brief online search it seems that this is a limitation of react-leaflet, but I wanted to check here first.

Also, is this the best way to set a popup for a newly created shape? I'm having a hard time translating the regular leaflet-draw approaches to react-leaflet-draw.

Answer

Evan Siroky picture Evan Siroky · Mar 20, 2017

It is possible to have react components inside a react-leaflet Popup. In your example you're using leaflet's API when instead you should be using react-leaflet's components. See the following example of showing a popup after clicking on a map:

const React = window.React;
const { Map, TileLayer, Marker, Popup } = window.ReactLeaflet;

let numMapClicks = 0

class SimpleExample extends React.Component {
    state = {}

  addPopup = (e) => {
    this.setState({
      popup: { 
        key: numMapClicks++,
        position: e.latlng
      }
    })
  }

  handleClick = (e) => {
    alert('clicked')
  }

  render() {
    const {popup} = this.state
    return (
      <Map 
        center={[51.505, -0.09]} 
        onClick={this.addPopup}
        zoom={13} 
        >
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
        {popup &&
          <Popup 
            key={`popup-${popup.key}`}
            position={popup.position}
            >
            <div>
              <p>A pretty CSS3 popup. <br/> Easily customizable.</p>
              <button onClick={this.handleClick}>Click Me!</button>
            </div>
          </Popup>
        }
      </Map>
    );
  }
}

window.ReactDOM.render(<SimpleExample />, document.getElementById('container'));

Here is a jsfiddle to demonstrate.