React Native Google map and programmatically change pin colors

Viewed 23

I built an app with React Native. The app maily shows markers in several locations.

<MapView
                style={styles.map}
                initialRegion={initialPosition}
                showsUserLocation={true}
                followsUserLocation={true}
                showsCompass={true}
                showsPointsOfInterest={false}
                customMapStyle={mapStyle}
                ref={(current) => (map.current = current)}
            >
                {
                    props.data.map((marker: any, index: number) => (
                        marker.single_point ?
                            <Marker
                                key={index}
                                coordinate={{
                                    latitude: Number(marker.single_point.split(',')[0].trim()),
                                    longitude: Number(marker.single_point.split(',')[1].trim()),
                                }}
                                ref={markerRefs[index]}
                                onPress={() => {
                                    setPin('aqua' === pin ? 'gold' : 'aqua')
                                    markerRefs[index].current.redraw()
                                }}
                                pinColor={pin}
                            >
                            </Marker>
                            : null
                    )
                    )}
            </MapView>

I added a state variable to change the pin color once clicked. The issue here is that the set of coordinates are sent to the map component as a prop. I did a copy of the prop and add to every object in the array an element/key named pincol

const [propCopy, setPropCopy] = useState([])
setPropCopy( props.data.map(v => ({...v, pincol: 'red'})))

but I'm getting the following error

ERROR  Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

I did this because my idea is to setPropCopy[index].pincol to green from the Marker onPress method.

What am I doing wrong? Thank you

1 Answers

You need to call set in a useEffect to avoid too many re-renders issues like this:

const [propCopy, setPropCopy] = useState([]);
useEffect(() => {
   setPropCopy( props.data.map(v => ({...v, pincol: 'red'})))
}, []);
Related