James Stewart
James Stewart

Reputation: 1054

Why is my map marker not rendering when generated via .map() in React Native?

Using React Native with react-native-maps on Android external device over Wifi.

I made a component called MapMarker which takes props title and coordinates. Inside my <MapView></MapView>, I can render it like so:

<MapMarker
  coordinates={{
      longitude: -4.516095,
      latitude: 55.679897
  }}
  title="James"
/>

But I want to render my markers dynamically, so I have a state set up like:

    mapMarkers: [
        {
            latLng: {
                latitude: 55.679897,
                longitude: -4.516095,
            },
            title: "James"
        }
    ]

And when I try to map this state using .map(), it doesn't seem to hit the component. I know this because I have a console.warn() inside my <Marker> component. This is how I am using the .map() function:

 {this.state.mapMarkers.map((marker) => {
    <MapMarker
       coordinates={{
           longitude: marker.latLng.longitude,
           latitude: marker.latLng.latitude
       }}
       title={marker.title}
   />
 })}

Using the second method, the console.warn() (which is placed in componentDidMount()) is not triggered. I have dumped out this.state.mapMarkers[0].longitude and latitude onto the main screen and they're both correct/visible.

From a Vue background so not 100% on what I need to do differently with .map() for rendering components.

Upvotes: 1

Views: 741

Answers (1)

Todd Chaffee
Todd Chaffee

Reputation: 6824

Make sure you return the React component you are creating. The easiest way to do this is to take advantage of your arrow function and use parens instead of function brackets.

 {this.state.mapMarkers.map((marker) => (
    <MapMarker
       coordinates={{
           longitude: marker.latLng.longitude,
           latitude: marker.latLng.latitude
       }}
       title={marker.title}
   />
 ))}

Upvotes: 3

Related Questions