javascript - Component state in ReactJS -
first of all, new in reactjs. display markers in mapcomponent. made work, honest think there should better way it... props parent component, loaded json. pass coordinates each item(from json) markers in state in mapcomponent. used react-google-maps solution google maps. maybe give me advice best approach in case? lot tips!
export class mapcomponent extends react.component { constructor(props) { super(props) this.state = { markers: [] } } getmarkers() { if (this.props.data.rows) { var markers = this.props.data.rows.map(function(item, i) { return { position: { lat: item.coordinate[0], lng: item.coordinate[1] }, item: item } }); this.setstate({ markers: markers }); } } shouldcomponentupdate(nextprops, nextstate) { return true; } componentdidupdate() { this.getmarkers(); } render() { return ( <div classname={styles.map}> <googlemaploader containerelement={ <div {...this.props} style={{ height: "100%", }} /> } googlemapelement={ <googlemap ref={(map) => console.log(map)} defaultzoom={9} defaultcenter={{lat: 52.379189, lng: 4.899431}}> {this.state.markers.map((marker, index) => { return ( <marker {...marker} /> ); })} </googlemap> } /> </div> ); } }
since passing state via props, can ovoid creating component class, need simple representational component, supported since 0.14 (i guess). representational components functions, representing render
function. functions take props
param
so component more clean:
const mapcomponent = (props) => { return ( <div classname={styles.map}> <googlemaploader containerelement={ <div {...props} style={{height: "100%"}} /> } googlemapelement={ <googlemap ref={(map) => console.log(map)} defaultzoom={9} defaultcenter={{lat: 52.379189, lng: 4.899431}}> {props.data.rows.map((item, index) => { const position = { lat: item.coordinate[0], lng: item.coordinate[1] }; return ( <marker key={index} position={position} item={item} /> ); })} </googlemap> } /> </div>); }
Comments
Post a Comment