javascript - React-Leaflet polygons are not being re-rendered -




i'm trying make dynamic polygons using react's state, leaflet polygons not being re-rendered.

the target create polygon user creates clicking in map.

class simpleexample extends react.component { constructor() {   super();   this.state = {     positions: [[51.505, -0.09]]   }; }  addposition = (e) => {   const {positions} = this.state   console.log('adding positions', positions)   positions.push([e.latlng.lat, e.latlng.lng])   this.setstate({positions}) }  render() {     console.log('should render new positions', this.state.positions)     const staticpositions = [[51.505, -0.09], [51.4958128370432, -0.10728836059570314], [51.49602657961649, -0.09956359863281251]]   return (     <map        center={[51.505, -0.09]}        onclick={this.addposition}       zoom={13}        >       <tilelayer         attribution='&copy; <a href="http://osm.org/copyright">openstreetmap</a> contributors'         url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'       />       <polygon positions={this.state.positions} color="blue" />       <polygon positions={staticpositions} color="red" />       <polyline positions={this.state.positions} />     </map>   ); } } 

please checkout fiddle: https://jsfiddle.net/cesargdm/j2g4ktsg/1/

you can copy in jsfiddle , should work. hope helps.

i have initial state empty array first click decides start drawing <polygon>, of course can use initial coordinate, that's totally you.

using arrow function (prevstate) => {} can update state depending on "previous state", here we're taking new coordinates , using concat() add our positions state.

you can find more information updating state here.

const react = window.react; const { map, tilelayer, marker, popup, polygon } = window.reactleaflet;  class simpleexample extends react.component {   constructor() {     super();     this.state = {       positions: []     };   }    addposition = (e) => {     const newpos = [e.latlng.lat, e.latlng.lng];     this.setstate(prevstate => (       {         positions: prevstate.positions.concat([newpos])       }     ));   }    render() {      return (       <map          center={[51.505, -0.09]}          onclick={this.addposition}         zoom={13}>         <tilelayer attribution='&copy; <ahref="http://osm.org/copyright">           openstreetmap</a> contributors'           url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'         />         <polygon positions={this.state.positions} color="blue" />       </map>     );   }  }  window.reactdom.render(<simpleexample />,    document.getelementbyid('container')); 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -