Search code examples
reactjsleafletreact-routerreact-domreact-leaflet

why component is not display in react?


I am trying to use leaflet in react ..I take reference of this module https://github.com/PaulLeCam/react-leaflet https://www.npmjs.com/package/react-leaflet but it not show map why ?

here is my code https://plnkr.co/edit/pTpPxhEFqouMrLTrKUFq?p=preview

// Code goes here

const { Map, TileLayer, Marker, Popup } = ReactLeaflet;
class A extends React.Component{
  constructor() {
    super();
    this.state = {
      lat: 51.505,
      lng: -0.09,
      zoom: 13,
    };
  }
  render(){
    return (
    const position = [this.state.lat, this.state.lng];
    return (

      <Map center={position} zoom={this.state.zoom}>
      <label>cccc</label>
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
        <Marker position={position}>
          <Popup>
            <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
          </Popup>
        </Marker>
      </Map>
    );
      )
  }
}

ReactDOM.render(<A/>,document.getElementById('example'));

Solution

  • You have two return statements in your render.

    render should only return the components once.

    render(){
        const position = [this.state.lat, this.state.lng];
        return (
    
          <Map center={position} zoom={this.state.zoom}>
          <label>cccc</label>
            <TileLayer
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
            />
            <Marker position={position}>
              <Popup>
                <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
              </Popup>
            </Marker>
          </Map>
        );
      }
    

    Multiple items:

    {this.state.items.map(item => (
        <Marker position={[item.lat, item.lng]}>
            <Popup>
                <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
            </Popup>
         </Marker
    
     )}