Shoaib Ahmed
Shoaib Ahmed

Reputation: 101

Calling handleClick before render()

I need to call the handleClick(e) before render() so that the range value is ready for the Marker. It's pretty much first react app and it's the only small issue left. First time I click, range value is empty, then it's the previous value instead of latest.

import React, { Component } from 'react';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import {LocationIcon} from './LocationIcon';
import Distance from './Distance'
var range, dist;
const MyMarker = props => {

  const initMarker = ref => {
    if (ref) {
      ref.leafletElement.openPopup()
    }
  }

  return <Marker ref={initMarker} {...props}/>
}

class User2View extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPos: null,
      range: 'k'};
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e){
    this.setState({ currentPos: e.latlng });
    localStorage.setItem('Poslat2', this.state.currentPos.lat);
    localStorage.setItem('Poslon2', this.state.currentPos.lng);
    const lat1 = localStorage.getItem('Poslat1');
    const lon1 = localStorage.getItem('Poslon1');
    const lat2 = localStorage.getItem('Poslat2');
    const lon2 = localStorage.getItem('Poslon2');
    dist = Distance(lat1, lon1, lat2, lon2);
    if (dist <= 1) {
      range = "User is in range"
    }
    else {
      range = "User is not in range"
    }
  }

  render() {
    return (
      <div>
        <Map center={this.props.center} zoom={this.props.zoom} onClick={this.handleClick}>
          <TileLayer
              url='https://{s}.tile.osm.org/{z}/{x}/{y}.png'
          />
          
          { this.state.currentPos && <MyMarker icon={LocationIcon}  position={this.state.currentPos}>
            <Popup position={this.state.currentPos}>
              <pre>{range}</pre>
            </Popup>
          </MyMarker>}
        </Map>
      </div>
    );
  }
}

export default User2View;

I had tried getDerivedStateFromProps and componentDidMount but nothing working.. Thank You

Upvotes: 0

Views: 84

Answers (1)

Cory Harper
Cory Harper

Reputation: 1055

If your range needs to be set to a certain value before the component mounts, that should go in the constructor. If it's okay for it to be set when the component mounts, you can put it in componentDidMount.

Here's some documentation to read up on lifecycle methods:

https://reactjs.org/docs/react-component.html#constructor
https://reactjs.org/docs/react-component.html#componentdidmount

Upvotes: 1

Related Questions