Search code examples
react-nativeconditional-rendering

Problem with conditional rendering in React Native


I have a map and i want a marker to appear when the user long-presses on a point. I have the following code:

    const [coords, setcoords] = React.useState(getcoord());
    const [show, setShow] = React.useState(false);

    const setPointCoords = (e) => {
        setcoords(e.geometry.coordinates);
        setShow(!show);
    }

    return (
        <View style={style.page}>
            <MapboxGL.MapView
                style={style.map}
                rotateEnabled={false}
                styleURL="mapbox://styles/daskalgg/ckp26fbmb34iv18otkav9sj4s"
                onLongPress={(e) => {
                    setPointCoords(e);
                }}
            >
                {
                    show &&
                    <MapboxGL.PointAnnotation
                        key="marker"
                        id="point"
                        draggable={true}
                        coordinate={coords} />
                }
            </MapboxGL.MapView>
            {
                show &&
                <Text>test</Text>
            }
        </View>
    );

The problem i have is that, although setPointCoords is called and the value of show changes, the marker never appears.

Some things i have noticed:

  1. The Text element, which is there for testing purposes, works as expected.
  2. The problem goes away when the initial value of show is true.

Solution

  • I found a solution but it's pretty hacky

                    <MapboxGL.PointAnnotation
                        key="marker"
                        id="point"
                        draggable={true}
                        onSelected={(e) => {
                            console.log(e);
                        }}
                        coordinate={coords} >
                        <View
                            key="marker"
                            style={{
                                borderColor: "black", backgroundColor: "red",
                                display: show ? 'flex' : 'none'
                            }}
                        >
                            <Text> This is a Marker </Text>
                        </View>
                    </MapboxGL.PointAnnotation>
    

    Since i can't control the style of the PointAnnotation itself, i display a View and control it's visibility through 'show'. I am not accepting it as the correct answer yet in hopes there is a better one.