I’m rendering markers into a react-native-map app. So I have in the backend API a defined type for each marker. Now I want to display them using customised icons.
Currently I render each type separately. Kind like this
//from API
this.setState({MyMarkers: (response.data)})
Type1mapMarkers = () => {
return this.state.MyMarkers.filter( report => report.type === 'type1').map((report) =>
<Marker
key={report.id}
coordinate={{ latitude: report.latitude, longitude:report.longitude }}
title={report.name}
description={report.info}
icon={require("../statics/icons/type1.png")}
>
<Image
source={require("../statics/icons/type1.png")}
style={{ width: 20, height: 20 }}
/>
</Marker >)
}
Type2mapMarkers = () => {
return this.state.MyMarkers.filter( report => report.type === 'type2').map((report) =>
<Marker
key={report.id}
coordinate={{ latitude: report.latitude, longitude:report.longitude }}
title={report.name}
icon={require("../statics/icons/type2.png")}
>
<Image
source={require("../statics/icons/type2.png")}
style={{ width: 20, height: 20 }}
/>
</Marker >)
}
render() {
return (
<SafeAreaView >
<View>
<MapView
...
>
{this.Type1mapMarkers()}
{this.Type2mapMarkers()}
</MapView>
</View>
</SafeAreaView>
);
}
Is there a way to work with an if statement in the rendering instead? I’ve tested a few options but not been succcesful. Any tips? What I’m trying to achieve is something like
this.setState({MyMarkers: (response.data)})
MapMarkers = () => {
return this.state.MyMarkers.map((report) =>
if (){
<Marker>
....
</Marker>}{
<Marker>
....
</Marker>}
}
render() {
return (
<SafeAreaView >
<View>
<MapView
...
>
{this.MapMarkers()}
</MapView>
</View>
</SafeAreaView>
);
}
2
Answers
Injecteer gave me the solution. But I made one adjustment to be able to have static path's.
I would use a straight-forward approach:
Note the use of string interpolation with `