Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return jsx from an outside function with callback?

I am trying to return jsx from outside my render method. It works when there is no api request, but as soon as I add the request and add a callback I can't return the jsx. How do I do this? renderLocations is being called in my render method.

renderLocations() {
    this.Geo((coord) => {
          return this.state.location.map((location, index) => {
            return (
              <div>
               {coord}
              </div>
            );
          })
        })
    }
like image 991
joethemow Avatar asked Jan 18 '26 03:01

joethemow


1 Answers

You should not do it like this.

A. You are not returning anything from renderLocations

B. If you are waiting for some data that will arrive later. Initiate the call in componentWillMount lifecycle method and upon arrival update the state of the component using this.setState({coord: coord}) - this would run the render method again. In the render method wherever you are calling the renderLocations method pass the this.state.coord

And change the renderLocations method like this

renderLocations(coord) {
  if (coord) {
    return this.state.location.map((location, index) => {
        return (
          <div>
           {coord}
          </div>
        );
      })
  }
}

Also, dont forget to initialize the state in getInitialState method or in the constructor.

like image 68
Arshabh Agarwal Avatar answered Jan 20 '26 20:01

Arshabh Agarwal